Sara Ree
Sara Ree

Reputation: 3543

change order of array based on another array

Let say we have our array like this:

let myArray = ["A", "B", "C", "D"]

What if we want to modify the order of elements in myArray based on modifier array so that, if myArray includes any element of modifier then we send that element to the end of the myArray

Like this:

let modifier =  ["B"] 
myArray = ["A", "C", "D", "B"] // B is sent to the end of myArray

And if we have this:

let modifier =  ["A", "C"]
myArray = ["B", "D", "A", "C"] // A and C are sent to the end of the array

I have tried looping and checking each array element against another but it went complicated...

Any help would be greatly appreciated.

Upvotes: 0

Views: 76

Answers (3)

Bilal Siddiqui
Bilal Siddiqui

Reputation: 3629

Very simple.

Step-1: Remove elements of modifier array from original array

 myArray = myArray.filter( (el) => !modifier.includes(el) );

Step-2: Push modifier array into original array

myArray = myArray.concat(modifier)

Update

As per demands in comments by seniors :) If use case is to move multiple data:

var myArray = ["A", "A", "A", "B", "B", "B", "C", "D", "E"];
var modifier = ["A", "B"];

// get static part
staticArray = myArray.filter( (el) => !modifier.includes(el) );

// get moving part
moveableArray = myArray.filter( (el) => modifier.includes(el) );

// merge both to get final array
myArray = staticArray.concat(moveableArray);

console.log(myArray);

Upvotes: 3

Abhishek Tiwari
Abhishek Tiwari

Reputation: 143

Simply use this to get desired result

    let myArray = ["A", "B", "C", "D"];
let modifier =  ["A", "C"];

for(let i=0;i<modifier.length;i++){
   if(myArray.includes(modifier[i])){
     myArray.splice(myArray.indexOf(modifier[i]), modifier[i]);
     myArray.push(modifier[i]);
   }
}
console.log(myArray);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386786

You could sort the array and move the items of modifier to the end of the array.

function sort(array, lastValues) {
    var last = Object.fromEntries(lastValues.map((v, i) => [v, i + 1]));
    return array.sort((a, b) => (last[a] || - Infinity) - (last[b] || - Infinity));
}

var array = ["A", "B", "C", "D"];

console.log(...sort(array, ["B"]));
console.log(...sort(array, ["A", "C"]));

Upvotes: 3

Related Questions