Skip to content

JavaScript reduce array of objects to array of strings | Example code

  • by

You can use map() function for reduce array of objects to array of strings in JavaScript. Basically map() performs an operation on every element of an array returning a new array.

It’s hard to do this with reduce() when you have such a small array, but still possible:

JavaScript reduce array of objects to array of strings

Simple example code. In this example a is the first item and b is the second item.

<!DOCTYPE html>
<html>
<body>

  <script>
    var obj = [
    {"text":"demo1"},
    {"text":"demo2"}
    ];
    var newArray = obj.reduce( (a,b) => [a.text, b.text])

    console.log(newArray)
  </script>

</body>
</html> 

Output:

JavaScript reduce array of objects to array of strings

You can use Array.prototype.map for that:

var arr = [
  {"text":"demo1"},
  {"text":"demo2"}
];
var texts = arr.map(function(el) {
  return el.text;
});
console.log(texts);

And with ES6, you can use arrow functions:

var texts = arr.map((el) => el.text);

More Examples

<script>
    var data = [ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ]

    var result = function(){
      var names = data.reduce(function(a, b){
        return  (a.name || a) + ',' + b.name
      })
      return names
    };

    var res = result();
    console.log(res)

</script>

Output: Bart,Lisa,Maggie

For a cleaner solution you can use map instead of reduce .(more readable )

var data = [ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ]
var result = data.map(x =>x.name).join(",");
console.log(result);

Reduce array to a single string

The first option is using the native js join method which eliminates the need for reduce.

  <script>

    var authors = ['some author', 'another author', 'last author'];
    var authorString = authors.join(",");
    console.log(authorString);

  </script>

Output: some author,another author,last author

Do comment if you have any doubts or suggestions on this JS reduce topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

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

Continue reading