Consider the scenario where I have three arrays representing names, number of books read, and levels of awesomeness:
let names = ["Mary", "Joe", "Kenan"];
let numberOfBooks = [2, 1, 4];
let awesomenessLevel = ["pretty cool", "meh", "super-reader"];
I attempted to merge these arrays into an array of objects using .reduce()
, but unfortunately, my attempts have not been successful:
let people = [
{
name: "Mary",
noOfBooks: 2,
awesomeness: "pretty cool"
},
{
name: "Joe",
noOfBooks: 1,
awesomeness: "meh"
},
{
name: "Kenan",
noOfBooks: 4,
awesomeness: "super-reader"
}
]
However, I was able to achieve the desired result using reduce as shown below:
let arrFinal = [];
names.reduce(function(all, item, index) {
arrFinal.push({
name: item,
noOfBooks: numberOfBooks[index],
awesomeness: awesomenessLevel[index]
})
}, []);