I am not able to push values from one array to another

I need to push values from one array to another.

var a = ['Hello World', 'Mono Space','Programming World'];
for (let i = 0; i < a.length; i++) {
   var abcd = [];
   abcd.push(a[i].split(' ').join('+'));
}

When I log the value of abcd to the console, only the last value appears. What could be the error?

The problem is that you’re assigning an empty array to abcd in each iteration, so only the last push remains – declare and initialise abcd outside of the loop instead. That said, you could also just .map() the original array like so:

var abcd = a.map(function (el) {
  return el.split(' ').join('+')
})

And instead of .split()ing and .join()ing the element, you might just .replace() all whitespace characters:

var abcd = a.map(function (el) {
  return el.replace(/\s/g, '+')
})

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.