0

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.

3 Answers 3

3

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);

Sign up to request clarification or add additional context in comments.

3 Comments

@JonasWilms what is your use case ? Please provide an example.
e.g. array=AAABBBCDE, modifier=AB
@georg : I have updated my answer with your use case as well.
3

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"]));

1 Comment

Fun fact: Infinity-Infinity = NaN. Since you already do i+1, why not just 0?
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.