问题
How can I merge arrays in JS so that the indexes of original elements in both arrays stays the same?
It seems that the spread array does not do what I needed:
let testArray: Array<any> = [];
testArray[4] = 'test4';
testArray[2] = 'test2';
testArray[15] = 'test15';
let otherTestArray = [];
otherTestArray[3] = 'test3';
otherTestArray[5] = 'test5';
console.log(testArray);
let testar = [...testArray, ...otherTestArray];
console.log(testar);
2:"test2"
4:"test4"
15:"test15"
19:"test3"
21:"test5"
Problem indexes for elements in new array, was changed.
So how can we solve this problem efficiently?
回答1:
You could take Object.assign and an array as target.
let testArray = [];
testArray[4] = 'test4';
testArray[2] = 'test2';
testArray[15] = 'test15';
let otherTestArray = [];
otherTestArray[3] = 'test3';
otherTestArray[5] = 'test5';
console.log(testArray);
let testar = Object.assign([], testArray, otherTestArray);
console.log(testar);
.as-console-wrapper { max-height: 100% !important; top: 0; }
回答2:
Sparse arrays are a pretty bad idea in general, but if you have to do this, you can use Object.assign
:
let testArray = [];
testArray[4] = 'test4';
testArray[2] = 'test2';
testArray[15] = 'test15';
let otherTestArray = [];
otherTestArray[3] = 'test3';
otherTestArray[5] = 'test5';
const finalArr = Object.assign([], testArray, otherTestArray);
console.log(finalArr);
// (16) [empty × 2, "test2", "test3", "test4", "test5", empty × 9, "test15"]
回答3:
You could iterate over each ignoring undefined values and assign the value to another array in the same position...
let testArray = [];
testArray[4] = 'test4';
testArray[2] = 'test2';
testArray[15] = 'test15';
//console.log(testArray);
let otherTestArray = [];
otherTestArray[3] = 'test3';
otherTestArray[5] = 'test5';
//console.log(otherTestArray);
let result = [];
for (var arr of [testArray, otherTestArray]){
console.log(arr.length);
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== void(0)) // ignore undefined values
result[i] = arr[i];
}
}
console.log(result);
来源:https://stackoverflow.com/questions/51188539/javascript-how-to-merge-arrays-so-that-the-indexes-of-original-elements-in-both