ol3dummy
ol3dummy

Reputation: 21

Javascript how to merge arrays so that the indexes of original elements in both arrays stays the same

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?

Upvotes: 1

Views: 615

Answers (3)

phuzi
phuzi

Reputation: 13060

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

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

Upvotes: 4

CertainPerformance
CertainPerformance

Reputation: 370689

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"]

Upvotes: 2

Related Questions