根据另一个数组更改数组的顺序

时间:2019-10-05 09:11:54

标签: javascript

假设我们有这样的数组:

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

如果我们想基于myArray数组修改modifier中元素的顺序,以便如果myArray包含modifier的任何元素,那么我们发送该元素到myArray

的末尾

赞:

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

如果我们有这个:

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

我已经尝试过对每个数组元素进行循环和检查,但这变得很复杂...

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:3)

非常简单。

步骤1:从原始数组中删除修饰符数组的元素

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

第2步:将修饰符数组推入原始数组

myArray = myArray.concat(modifier)

更新

根据老年人的评论要求:)如果用例是移动多个数据:

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

答案 1 :(得分:3)

您可以对数组进行排序,并将modifier的项目移到数组的末尾。

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

答案 2 :(得分:1)

只需使用它即可获得所需的结果

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