-2

I have an array with identical values inside it. I want to create an array inside the array containing the name as well as the number of times it had occur in the array. Here's an example of the input and output:

Input:

['apple', 'apple', 'apple', 'pear', 'pear', 'orange', 'apple', 'orange']

will output:

[{'name': 'apple', 'number': 4}, {'name': 'orange', 'number': 2}, {'name': 'pear', 'number': 2}]
  • 1
    There are plenty of questions about counting the occurrences in an array. Please add the the research and the code you have tried. – adiga Feb 03 '21 at 13:38
  • Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan Feb 03 '21 at 13:45

2 Answers2

0

One of the ways of achieving this:

let arr = ['apple', 'apple', 'apple', 'pear', 'pear', 'orange', 'apple', 'orange'];

let result = arr.reduce((acc, curr) => {
   let existingEntry = acc.find(item => item.name === curr);
   if(existingEntry) {
       existingEntry.number ++;
   } else {
      acc.push({name: curr, number: 1});
   }
   return acc
}, []);

console.log(result);
Raeesaa
  • 3,267
  • 2
  • 22
  • 44
0

let a = ['apple', 'apple', 'apple', 'pear', 'pear', 'orange', 'apple', 'orange']
let b = a.reduce((a, cur) => {
  if (!a[cur]) a[cur] = 1
  else a[cur]++
  return a
}, {})
let c = Object.keys(b).map(v => ({
  name: v,
  number: b[v]
}))
console.log(c)
KhaiTran
  • 111
  • 3