对数组进行排序并将元素添加到该数组索引中的特定位置

Sorting an array and add elements to a specific place in the index of that array

我有一个数组需要排序,但一些对象也需要复制到新数组中。

var arr = ["880163305_0010-DI03390REY-D", "880163305_0010", "880163305_0020-DI03390REY-D", "880163305_0020", "880163305_0030-DI03390REY-D", "880163305_0030"];
console.log(arr);

let evenArray=arr.filter((a,i)=>i%2===0);
console.log(evenArray);

这是我的原始数组。

[
  "880163305_0010-DI03390REY-D",
  "880163305_0010",
  "880163305_0020-DI03390REY-D",
  "880163305_0020",
  "880163305_0030-DI03390REY-D",
  "880163305_0030"
]

我的新数组应该是:

[
  "880163305_0010-DI03390REY-D",
  "880163305_0010",
  "880163305_0010-DI03390REY-D"
  "880163305_0020-DI03390REY-D",
  "880163305_0020",
  "880163305_0020-DI03390REY-D"
  "880163305_0030-DI03390REY-D",
  "880163305_0030"
  "880163305_0030-DI03390REY-D"
]

我试图创建第二个数组,其中只有偶数,因为这些是我需要添加的。

let evenArray=arr.filter((a,i)=>i%2===0);

然后我尝试将 evenArray 添加到 arr,但我找不到为此的方法。 我很新@this。 感谢您的帮助。

您可以 map 通过 evenArray 和 return 现有 arr 中的 i * 2i * 2 + 1 元素,然后是evenArray.

对应项

const arr = [
    "880163305_0010-DI03390REY-D", "880163305_0010", 
    "880163305_0020-DI03390REY-D", "880163305_0020", 
    "880163305_0030-DI03390REY-D", "880163305_0030"
];

const evenArray = arr.filter((a, i) => i % 2 === 0);

const result = evenArray.flatMap((a, i) => {
  return [arr[i * 2], arr[i * 2 + 1], a];
});

console.log(result);