1

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?

2
  • 1
    Try using a reduce? Maybe you can share your attempts so far? Commented Oct 22, 2020 at 14:46
  • 1
    why taking backticks for strings? Commented Oct 22, 2020 at 14:46

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.