2

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.

Can anybody help with this. Thanks in advance.

2
  • 2
    a space is not an empty string. what have you tried? Commented Mar 17, 2022 at 11:11
  • a for loop over the indices. if empty string get the value for that index from a? Commented Mar 17, 2022 at 11:13

1 Answer 1

2

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

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

Comments

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.