-2

I have an object, which I need to add up to a number of times words appear. Ex:

{
step1: ["luiz"]
step2: ["pedro"]
step3: ["luiz"]
step4: ["luiz"]
step5: ["luiz"]
}

I tried using .map, .forEach, .filter, but they all come back undefined.

.filter

let irmas = answers.filter((answer) => answer[1] === 'luiz)

.map

let contagemRespostas = answers.map(function(answer, index) {
      return contagemRespostas.index
    })

How do I get names only and add values?

EDIT:

The return is something like:

{ 'luiz': 3, 'pedro': 2 } or the highest value { 'luiz': 3 }

Luiz Henrique
  • 103
  • 1
  • 11

2 Answers2

2

You could use a reduce to create an object with the values

const data = {
  step1: ["luiz"],
  step2: ["pedro"],
  step3: ["luiz"],
  step4: ["luiz"],
  step5: ["luiz"],
}
    
const result = Object.values(data).flat().reduce((acc, cur) => {
  acc.hasOwnProperty(cur) ? acc[cur]++ : acc[cur] = 1
  return acc
}, {})

console.log(result) // {luiz: 4, pedro: 1}
1

Try something like this:

https://jsfiddle.net/bwmfhqev/2/

var foo = {
    step1: ["luiz"],
    step2: ["pedro"],
    step3: ["luiz"],
    step4: ["luiz"],
    step5: ["luiz"]
}

let result = {};

console.log(Object.keys(foo));

// loop over the keys of the object
for(var key of Object.keys(foo)) {
    // get the number of occurrences of words in the array for each key
    let count= foo[key].reduce((a,c)=> (a[c]=++a[c]||1,a) ,{});
  //combine everything into 1 object
  for(var key2 of Object.keys(count)) {
    console.log(count[key2]);
    if(key2 in result) {
        result[key2] = result[key2] + count[key2];
    }
    else {
        result[key2] = count[key2];
    }
  }
}

console.log(result);

The idea here to process each key in the original object. and then create an object out of each one that gets the number of occurrences of each word for each key. Then combine them all into 1 object

Rohan Bhangui
  • 353
  • 2
  • 10