如何复制js数组中的元素?

时间:2015-10-23 14:42:32

标签: javascript arrays

最简单的方法(使用“原生”javascript)复制javascript数组中的每个元素?

订单很重要

例如:

a = [2, 3, 1, 4]
// do something with a
a
// a is now [2, 2, 3, 3, 1, 1, 4, 4]

11 个答案:

答案 0 :(得分:13)

我想出了类似于tymeJV的答案

[2, 3, 1, 4].reduce(function (res, current, index, array) {
    return res.concat([current, current]);
}, []);

答案 1 :(得分:7)

基本上:

a = [2, 3, 1, 4];
b=[];

for(var i = 0; i< a.length;++i){
  b.push(a[i]);
  b.push(a[i]);
}

a=b;

答案 2 :(得分:5)

我想你可以这样做:

var duplicated = a.map(function(item) {
    return [item, item];
}).reduce(function(a, b) { return a.concat(b) });

//duplicated: [2, 2, 3, 3, 1, 1, 4, 4]

答案 3 :(得分:4)

我在我的应用程序中遇到了这个问题,所以我创建了这个函数:

function duplicateElements(array, times) {
  return array.reduce((res, current) => {
      return res.concat(Array(times).fill(current));
  }, []);
}

要使用它,只需传递数组,以及希望元素重复的次数:

duplicateElements([2, 3, 1, 4], 2);
// returns: [2, 2, 3, 3, 1, 1, 4, 4]

答案 4 :(得分:1)

只需拼接一下。

var a = [2, 3, 1, 4],
    i = a.length;
while (i--) {
    a.splice(i, 0, a[i]);
}
document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>');

答案 5 :(得分:1)

基本上,您可以在ES19中使用flatMap

a = [1, 2, 3, 4];
a.flatMap(i => [i,i]); // [1, 1, 2, 2, 3, 3, 4, 4]

您还可以像这样自定义重复编号:

a = [1, 2, 3, 4];
const dublicateItems = (arr, numberOfRepetitions) => 
    arr.flatMap(i => Array.from({ length: numberOfRepetitions }).fill(i));

dublicateItems(a, 3);

答案 6 :(得分:0)

这些函数可能有助于查看.sort(),. concat()

function duplicate(arr) {
    return arr.concat(arr).sort()
} 
console.log(duplicate([1,2,3,4,5]))

答案 7 :(得分:0)

0/2  =  0    =  0  |0  =  0
1/2  =  0.5  =  0.5|0  =  0
2/2  =  1    =  1  |0  =  1
3/2  =  1.5  =  1.5|0  =  1
4/2  =  2    =  2  |0  =  2
5/2  =  2.5  =  2.5|0  =  2
6/2  =  3    =  3  |0  =  3
7/2  =  3.5  =  3.5|0  =  3

|0视为Math.floor

在代码中,这可能如下所示:

for (let i = 0; i < a.length * 2; i++) {
  a[i] = a[i / 2 | 0]
}

因为不变性是可取的,所以可以这样做:

function repeatItems(a, n) {
  const b = new Array(a.length * n)
  for (let i = 0; i < b.length; i++) {
    b[i] = a[i / n | 0]
  }
  return b
}

不可读的ES6意大利面条代码:

const repeatItems = (a, n) => Array.from(Array(a.length * n), (_, i) => a[i / n | 0])

答案 8 :(得分:0)

ES6的生活方式(基于axelduch's答案)

const arr = [2, 3, 1, 4].reduce((res, current) => [...res, current, current], []);

console.log(arr);

答案 9 :(得分:0)

怎么样?

for (i=a.length-1;i>=0;i--)a.splice(i,0,a[i]);

向后迭代的价值被低估了,在这种情况下,它使索引保持完整;)

答案 10 :(得分:0)

有很多方法可以将项目添加到数组中,如上所示。我已经比较了它,您可以在控制台中自己查看性能。 无论什么时间都在两个“ console.time”之间

console.clear();

function loopMyArray(){
 var loopArray = new Array(10000);
 for(var i = 0; i < loopArray.length; i++){
   loopArray[i] = i+1;
 }
 console.log(loopArray);
}
console.time('loopMyArray');
loopMyArray();
console.timeEnd('loopMyArray');

function fillArray(){
 let x = 0;
 let filledArray = new Array(10000).fill(null).map(()=> ++x);
 console.log(filledArray);
}

console.time('fillArray');
fillArray();
console.timeEnd('fillArray');

function keyMyArray(){
 let fromKeyArray = Array.from(Array(10000).keys());
 console.log(fromKeyArray);
}
console.time('keyMyArray');
keyMyArray();
console.timeEnd('keyMyArray');

function spreadKeysArray(){
 let spreadArray = [...Array(10000).keys()];
 console.log(spreadArray);
}
console.time('spreadKeysArray');
spreadKeysArray();
console.timeEnd('spreadKeysArray');

console.log(' Start from 1');

function mapKeyArray(){
 //let mapArray = ([...Array(1000).keys()].map(x => x++)); //increment after return
 let mapArray = [...Array(10000).keys()].map(x => ++x);
 console.log(mapArray);
}

console.time('mapKeyArray');
mapKeyArray();
console.timeEnd('mapKeyArray');

function sliceKeyArray(){
 let sliceFirstElementArray = [...Array(10000+1).keys()].slice(1);
 console.log(sliceFirstElementArray);
}
console.time('sliceKeyArray');
sliceKeyArray();
console.timeEnd('sliceKeyArray');

function calcFromLength(){
 let fromLengthArray = Array.from({length: 10000}, (v, k) => k+1);
 console.log(fromLengthArray);
}
console.time('calcFromLength');
calcFromLength();
console.timeEnd('calcFromLength');

console.log('======== add a double for every item ========');

function mapDoubleArray(){
 // adding 1,1,2,2,3,3 etc
 let doubleArray = [...Array(10000).keys()].map(x => Math.floor(++x/2) + x%2);
 console.log(doubleArray);
}
console.time('mapDoubleArray');
mapDoubleArray();
console.timeEnd('mapDoubleArray');

function fromDoubleArray(){
 let fromDoubleArray = Array.from({length: 10000}, (v, x) => Math.floor(++x/2) + x%2);
 console.log(fromDoubleArray);
}
console.time('fromDoubleArray');
fromDoubleArray(); // Whatever is timed goes between the two "console.time"
console.timeEnd('fromDoubleArray');

function doubleSpreadArray(){
 let keyArray = [...Array(500+1).keys()].slice(1);
 let doubleSpreadArray = [...keyArray,...keyArray];
 console.log(doubleSpreadArray);
}
console.time('doubleSpreadArray');
doubleSpreadArray(); // Whatever is timed goes between the two "console.time"
console.timeEnd('doubleSpreadArray');

function reduceDoubleArray(){
 let reduceDoubleArray = Array.from({length: 5000}, (v, k) => k+1).reduce((m,i) => m.concat([i,i]), []);
 console.log(reduceDoubleArray);
}
console.time('reduceDoubleArray');
reduceDoubleArray(); // Whatever is timed goes between the two "console.time"
console.timeEnd('reduceDoubleArray');