Search code examples
javascriptarraysreduceaccumulator

Combine several arrays into an array of objects in JavaScript


Say I have three arrays depicting some names, number of books read and how awesome these people [in names] are:

let names = ["Mary", "Joe", "Kenan"];
let numberOfBooks = [2, 1, 4];
let awesomenessLevel = ["pretty cool", "meh", "super-reader"];

I'm trying to use .reduce() to bring them together to create an array of objects containing the relevant index in each array, but I am failing miserably:

    let people = [
    {
       name: "Mary",
       noOfBooks: 2,
       awesomeness: "pretty cool"
    },
    {
       name: "Joe",
       noOfBooks: 1,
       awesomeness: "meh"
    },
    {
       name: "Kenan",
       noOfBooks: 4,
       awesomeness: "super-reader"
    }
  ]

I got it with reduce as well:

let arrFinal = [];

 names.reduce(function(all, item, index) {
  arrFinal.push({
    name: item,
    noOfBooks: numberOfBooks[index],
    awesomeness: awesomenessLevel[index]
  })
}, []);

Solution

  • You could do it with map, like this:

    let result = names.map( (v, i) => ({
        name: names[i], 
        noOfBooks: numberOfBooks[i],
        awesomenessLevel: awesomenessLevel[i]
    }));
    

    let names = ["Mary", "Joe", "Kenan"];
    let numberOfBooks = [2, 1, 4];
    let awesomenessLevel = ["pretty cool", "meh", "super-reader"];
    
    let result = names.map( (v, i) => ({
        name: names[i], 
        noOfBooks: numberOfBooks[i],
        awesomenessLevel: awesomenessLevel[i]
    }));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    map works better than reduce in this case, because the number of elements you have in the names array (or any of the two others) is the same as the number of elements you need in the output. In that case it is more natural to use map.