1

Suppose you have the following array:

const arr = [
  {'stars': 5},
  {'stars': 4},
  {'stars':5}
]

How would one go about extracting all the integers from the 'stars' keys, and pushing them into an array?

I've tried the following

arr.map(item => {
  let arr = []
  arr.push(...arr,item.stars)
  console.log(arr)
})

...but it just pushes each number into it's own array, as follows:

[5] [4] [5]

What is I want is an array that looks like this: [5,4,5]

Suggestions?

Josh Simon
  • 159
  • 1
  • 10
  • 27

3 Answers3

0

You should return the result you want for each element.

Then, you assign the result of map to some new array.

const arr = [
  {'stars': 5},
  {'stars': 4},
  {'stars': 5}
];
const res = arr.map(item => {
  return item.stars;
});
console.log(res);
// [ 5, 4, 5 ]

See also the docs for Array.prototype.map()

costaparas
  • 5,047
  • 11
  • 16
  • 26
0

You can just use Array#map

const arr = [
  {'stars': 5},
  {'stars': 4},
  {'stars':5}
]

const newArr = arr.map(a=>a.stars)

console.log(newArr)
ptothep
  • 415
  • 3
  • 10
0

If you want to loop the array of object to create a new array, you could do like this


const arr = [
  {'stars': 5},
  {'stars': 4},
  {'stars':5}
]

let newArr = [];

for (let i=0; i<arr.length; i++) {
   newArr.push(arr[i].stars);
}

console.log(newArr); // [5,4,5]
 
ridoansaleh
  • 604
  • 9
  • 20