JS - Find the same occurrences in text and count them

I have written code which is counting the same occurrence in text and show how many iterations are there.

What is better way to write code like this?

const arr = ['delta delta delta alfa beta beta alfa delta delta delta alfa beta beta alfa'];
let chunkArr =  arr.join(' ').split(' ');

const counterSameOcurancces = chunkArr.reduce((arr, w) => {
    arr[w] = ++arr[w] || 1;
    return arr;
}, {});

console.log(counterSameOcurancces); // [delta: 6, alfa: 4, beta: 4]

Thank you a lot :slight_smile:

What issues do you think that it has? Is there some other way that you think should be used instead?

1 Like

to build cleaner code and use e.g. ternary operator?

 const arrWithStrings = arr[0].split(' ')

    const result = arrWithStrings.reduce((arr, w) => {
        arr[w] = w in arr ? ++arr[w] : 1;
        return arr
    }, {});

In that example, it seems that the ternary operator makes this more confusing than not.

What does the code look like after fixing problems reported by a linter such as JSLint?

const arr = [
    "delta delta delta alfa beta beta alfa",
    "delta delta delta alfa beta beta alfa"
];

function countWord(obj, word) {
    obj[word] = (obj[word] || 0) + 1;
    return obj;
}

const chunkArr =  arr.join(" ").split(" ");
const counterSameOccurances = chunkArr.reduce(countWord, {});

console.log(counterSameOccurances); // [delta: 6, alfa: 4, beta: 4]

That looks to be a lot more improved.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.