Javascript函数从数组中的位置删除

时间:2017-07-06 07:13:43

标签: javascript ecmascript-6

我有一个数组:

var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];

我需要从数组中删除每个第3项并将其添加到另一个数组中。

最终结果应为:

var myArray = [12, 11 18, 30, 21, 18];

var secondArray = [13, 51, 20];

我该怎么做?

5 个答案:

答案 0 :(得分:2)

迭代数组并拼接每个第3个元素并推送到第二个数组。



var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
var secondArray = [];
for (var i = 2; i < myArray.length; i += 2) {
  secondArray.push(myArray[i]);
  myArray.splice(i, 1);
}

console.info('myArray', myArray)
console.info('secondArray', secondArray)
&#13;
&#13;
&#13;

答案 1 :(得分:1)

&#13;
&#13;
var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];

var newArray1 = [];
var newArray2 = [];
myArray.forEach(function(value,index){
  if((index + 1) % 3 === 0){
    newArray1.push(value);
  }
  else {
    newArray2.push(value);
  }
});

console.log(newArray1); // Stores element at index 3 in the original array
console.log(newArray2); // Stores element at index other than 3 in the original array
&#13;
&#13;
&#13;

答案 2 :(得分:1)

Array#reduce原始数组分为2个新数组:

&#13;
&#13;
const myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];

const [without3rdItems, with3rdItems] = myArray.reduce((arrs, n, i) => {
  const arr = (i + 1) % 3 ? 0 : 1;
  
  arrs[arr].push(n);
  
  return arrs;
}, [[], []]);

console.log(without3rdItems.join());
console.log(with3rdItems.join());
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我不喜欢拼接源数组的示例,因为拼接是一个很长的操作,而在大型数组/多个操作中,它将不那么有效。我认为你应该创建新的数组并且不介意。

NSMutableDictionary

答案 4 :(得分:0)

var a = [12, 11, 13, 18, 30, 51, 21, 18, 20];
var b = [ ];
var l = a.length;
for(i = 2; i < l; i += 2){
    b.push(a[i]);
    a.splice(i, 1);
    l--;
}
console.log("Array a: ", a);
console.log("Array b: ", b);