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

JavaScript array comparisions and display values from another

I have a case where I need to compare between two arrays and display values from another.;
For example, I have two arrays:

let a = ['a','b','c'];
let b = ['textA' 'textB', ' '];

So, I am basically trying to loop over the array b and display value like this:

   textA
   textB
   C

So, when there are any empty values found in array b, display the same indexed values from array a.

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

Can anybody help with this. Thanks in advance.

>Solution :

you can :

  • trim the value to see if there is empty or only space
    elem.trim().length
  • if string is empty check if data in other array exist if (!elem.trim().length && a[index])
let a = ['a','b','c'];
let b = ['textA', 'textB', ' '];

b.forEach((elem, index) => {
  if (!elem.trim().length && a[index]) {
    console.log(a[index]);
  } else {
    console.log(elem);
  }
});

One other solution consist to create a result array with array.map and display all key of this new array

let a = ['a','b','c'];
let b = ['textA', 'textB', ' '];


let result = b.map((elem, index) => (!elem.trim().length && a[index]) ? a[index] : elem);

console.log(result);
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