Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace element from first array by another element of second array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading