0

I am having this issue replacing element from first array by another element of second array.

For exapmle if I have one array haiving some empty values and string like this:

let array_1 = [empty, 'Connected', empty, 'Connected', 'Connected'];

And another new array will be like this:

let array_2 = [empty, 'Updated'];

So, New updated array with replaced element will look like this:

newArray = [empty, 'Updated', empty, 'Connected', 'Connected'];

I tried with for loop and by using findIndexof, but could not replace the element with exact index address.

One of them which worked for me partially is:

console.log(Object.values(...array_1, ...array_2));

Out of above line is just one array with one element, not reast of element from array_1:

['Updated']

But it seems like Obejct.values() does not work with element generated as a empty.

Any possible solution on this would be great!

1 Answer 1

3

If I understood it properly you can solve it by using map function like this:

let array_1 = [undefined, "Connected", undefined, "Connected", "Connected"];
let array_2 = [undefined, "Updated"];

const res = array_1.map((val, idx) => {
  return array_2[idx] || val;
});
console.log(res);

Sign up to request clarification or add additional context in comments.

3 Comments

Could you explain it in brief? that would be nice. And tell how empty element from the array behaves like?
Yeah sure, and empty element in a javascript array is always assigned as undefined, And this map loops the array one and returns or the values of the same position of the array 2 or if the array 2 has no values for this position return the val of the first array
Execellent! But when I checked with console.log(typeof array2[0]) it showed me undefined, but in for loop or map function it did't show me anything. why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.