Emile Caron
Emile Caron

Reputation: 29

How to count values in an array and set them in an object within a new array? (Javascript)

So basically I have an array with a ton of words. I want to achieve a new array that holds the word and amount of the word as properties of an object. Like so:

const arrayWithWords = [`word1`, `word2`, `word5`, `word1`, `word3`, `word6`, `word2`, `word3`, `word1`, `word5`]

// and I want to achieve the array below

const newArray = [ {name: `word1`, amount: 3} {name: `word2`, amount: 2} {name: `word3`, amount: 2} {name: `word4`, amount: 0} {name: `word5`, amount: 2} {name: `word6`, amount:1}]

I've tried using the for-loop but I'm always getting stuck. What could be a possible solution for this?

Upvotes: 1

Views: 59

Answers (3)

deepak thomas
deepak thomas

Reputation: 1180

You can easily do it by converting the array into a map and counting them using the map as given bellow

const arrayWithWords = [`word1`, `word2`, `word5`, `word1`, `word3`, `word6`, `word2`, `word3`, `word1`, `word5`]
let arrayMap={};
arrayWithWords.forEach((word)=>{
    arrayMap[word] = arrayMap[word] ? arrayMap[word] + 1 : 1;
});
const newArray = Object.keys(arrayMap).map(key=>{
    return {name:key,amount:arrayMap[key]};
});
console.log(newArray);

Upvotes: 1

Derek Wang
Derek Wang

Reputation: 10193

Using Array.prototype.reduce, you can get the count for the same items in an array.

const input = [`word1`, `word2`, `word5`, `word1`, `word3`, `word6`, `word2`, `word3`, `word1`, `word5`];

const groupedBy = input.reduce((acc, cur) => {
  acc[cur] ? acc[cur]['amount'] ++ : acc[cur] = {
    name: cur,
    amount: 1
  };
  return acc;
}, {});
const result = Object.values(groupedBy);
console.log(result);

Upvotes: 2

phi-rakib
phi-rakib

Reputation: 3302

You can easily solve it by counting the frequencies.

const arrayWithWords = [
  `word1`,
  `word2`,
  `word5`,
  `word1`,
  `word3`,
  `word6`,
  `word2`,
  `word3`,
  `word1`,
  `word5`,
];

let ret = arrayWithWords.reduce((p, c) => {
  if (!p[c]) p[c] = 1;
  else p[c] += 1;
  return p;
}, {});

ret = Object.entries(ret).map((x) => ({ name: x[0], amount: x[1] }));
console.log(ret);

Upvotes: 2

Related Questions