Home > Net >  count each duplicate value in object and increase
count each duplicate value in object and increase

Time:11-21

im struggling with following logic.

I am creating following array of objects upon running through a given string.

[{"word":"Frank","c":1},
{"word":"Irina","c":1},
{"word":"Frank","c":1},
{"word":"Frank","c":1},
{"word":"Thomas","c":1}]

what i want to achieve is:

[{"word":"Frank","c":3},
{"word":"Irina","c":1},
{"word":"Thomas","c":1}]

what would be the best way here?

I am sending the string to this function and create the array. but im not able to get what I want.

function words(str) { 
          return str.split(" ").reduce(function(count, word) {

            if(word.length>2&&isLetter(word)){
              data.push({word:word, count: 1});
            }
          }, {});
      }

thanks for some help Adrian

CodePudding user response:

You can use object accumulator to keep count of each word and then using Object.values() get all the values.

function words(str) {
  return Object.values(str.split(" ").reduce((result, word) => {
    result[word] ??= {word, count: 0};
    result[word].count  = 1;
    return result;
  }, {}));
}

console.log(words("Frank Irina Frank Frank Thomas"));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Assuming that c is not always 1 (in which case you can do as the other post suggested and just keep count of the words), you can do it like this, looping through the data and summing the c values in a buffer, using word as the key for the buffer. Then map the buffer values to a final array.

const data = [{"word":"Frank","c":1},
{"word":"Irina","c":1},
{"word":"Frank","c":1},
{"word":"Frank","c":1},
{"word":"Thomas","c":1}];

//console.log(data);

let buffer = {};
data.forEach(i=>{
  let w = i.word;
  let words = buffer[w] || {word: w, c: 0};
  words.c = i.c*1   words.c;
  buffer[w] = words;
});

let final = Object.values(buffer).map(b=>{
  return {word: b.word, c: b.c};
});

console.log(final);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

This will work for any values of c:

const data = [{"word":"Frank","c":2},
{"word":"Irina","c":4},
{"word":"Frank","c":1},
{"word":"Frank","c":3},
{"word":"Thomas","c":1}];

//console.log(data);

let buffer = {};
data.forEach(i=>{
  let w = i.word;
  let words = buffer[w] || {word: w, c: 0};
  words.c = i.c*1   words.c;
  buffer[w] = words;
});

let final = Object.values(buffer).map(b=>{
  return {word: b.word, c: b.c};
});

console.log(final);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related