Home > Software design >  How can I move items from an array from one position to another?
How can I move items from an array from one position to another?

Time:01-05

const elementeSelected = ["a", "b"];
const allElements = ["m", "s", "e", "r", "q", "d", "a", "b", "c"];

// result allElements = ["a", "b", "m", "s", "e", "r", "q", "d", "c"];

https://codesandbox.io/s/distracted-lederberg-yji13f?file=/src/index.js:0-175

I tried to reorder the items form allElement. I want the items from elementeSelected to be move from their position in allElements to the first position.

CodePudding user response:

You need to concat the arrays together and remove the ones that were already used. You can do that with spread syntax and with filter. The filter uses includes to check if it is duplicated.

const elementeSelected = ["a", "b"];
const allElements = ["m", "s", "e", "r", "q", "d", "a", "b", "c"];

const result = [...elementeSelected, ...allElements.filter(n => !elementeSelected.includes(n))];

console.log(result);

CodePudding user response:

var allelements = ["m", "s", "e", "r", "q", "d", "a", "b", "c"];
var x= 6;
var pos=0;
var temp=allelements[x];
var i;
for (i=x; i>=pos; i--)
    {
       allelements[i]=allelements[i-1];
    }
allelements[pos]=temp;

var y= 7;
var pos2=1

<!-- begin snippet: js hide: false console: true babel: false -->

var temp2=allelements[y];
var i;
for (i=y; i>=pos2; i--)
    {
       allelements[i]=allelements[i-1];
    }
alllements[pos2]=temp2;
console.log(allelements);

CodePudding user response:

There are several ways you can rearrange the elements in an array. Here are a few options:

Use the splice() method to remove elements from the array and then reinsert them at a new position. For example, to move the "a" and "b" elements to the beginning of the array, you can do:

let a = allElements.indexOf("a");
let b = allElements.indexOf("b");

allElements.splice(a, 1);
allElements.splice(b, 1);

allElements.unshift("a", "b");

Use the sort() method to sort the array in the order you want. For example:

allElements.sort((a, b) => {
  if (a === "a") return -1;
  if (b === "a") return 1;
  if (a === "b") return -1;
  if (b === "b") return 1;
  return 0;
});

Note that these examples modify the original array.

  • Related