简体   繁体   English

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

[英]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如果我们想根据modifier数组修改myArray中元素的顺序,如果myArray包含modifier的任何元素,那么我们将该元素发送到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.任何帮助将不胜感激。

Very simple.很简单。

Step-1: Remove elements of modifier array from original array步骤 1:从原始数组中删除修饰符数组的元素

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

Step-2: Push modifier array into original array Step-2:将修饰符数组推入原始数组

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

You could sort the array and move the items of modifier to the end of the array.您可以对数组进行排序并将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"]));

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM