Home > Blockchain >  Count array of strings with reduce
Count array of strings with reduce

Time:12-11

I am trying to count how many identical values there are in an array of strings using reduce but this.

const arrayOfStrings = ["63955a83c1a9a4d5365b686c", "63955e3e478e25a859a6e7bb", "63955e3e478e25a859a6e7bb"]

const result = arrayOfStrings.reduce((prev, curr) => {
  prev[curr] = prev[curr] || [{
    id: curr,
    amount: 0
  }];
  prev[curr][curr.amount]  = 1
  return prev;
}, [])

I'm currently getting a strange array, but it's not even close to what I want, I'm expecting something like this:

[
  {
    id: "63955a83c1a9a4d5365b686c",
    amount: 1
  },
  {
    id: "63955e3e478e25a859a6e7bb",
    amount: 2
  }
]

CodePudding user response:

  1. You need to initialise your reduce with an object rather than an array.

  2. Update the amount by assigning the value to acc[c].amount.

  3. Extract the values (the nested objects) with Object.values.

const arr = ["63955a83c1a9a4d5365b686c", "63955e3e478e25a859a6e7bb", "63955e3e478e25a859a6e7bb"];

const out = arr.reduce((prev, curr) => {
  prev[curr] ??= { id: curr, amount: 0 };
  prev[curr].amount  = 1;
  return prev;
}, {});

console.log(Object.values(out));

CodePudding user response:

You can use find inside reduce to search whether the value is already present in the array and if yes, then update the amount value, otherwise initialize a new object and push it in the array.

const arrayOfStrings = ["63955a83c1a9a4d5365b686c", "63955e3e478e25a859a6e7bb", "63955e3e478e25a859a6e7bb"]

const result = arrayOfStrings.reduce((prev, curr) => {
  let o = prev.find((obj) => obj.id === curr)
  o ? o.amount   : prev.push({ id: curr, amount: 1 })
  return prev;
}, [])

console.log(result)
 

  • Related