Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

35
Views
count each duplicate value in object and increase

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

7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

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

7 months ago · Juan Pablo Isaza Report

0

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

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

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs