Home > other >  How to count each element number in array in javascript
How to count each element number in array in javascript

Time:09-28

//I have three word in array 'good','is','good'

let arr = ['good','is','good']

//In arr,the word 'good' show 2 times,the word 'is' show 1 time.And I use this code to count show times

arr.reduce((prev, next) => {
  prev[next] = prev[next]   1 || 1;
  return prev;
}, []);

//The result is [good:2,is:1]

//But Here is important,What I want is this format.[good:1,is:1,good:2]

//The arr[0] good,first time show,value = 1,the arr[2] good,second time show,value = 2

//How to get this format?

CodePudding user response:

You can use the counting code in a map:

let arr = ['good','is','good']

const result = arr.map((() => {
  const count = {};
  return el => {
    count[el] = count[el]   1 || 1;
    return {[el]: count[el]};
  }
})())
console.log(result);

CodePudding user response:

let arr = ['good','is','good']

arr=arr.reduce((prev, next) => {
  const x = prev.find(i=>i[next]);
  const occurance = x ? x[next] 1:1;
  prev.push({[next]: occurance})
  return prev;
}, []);

console.log(arr)
  • Related