JS - Find the same occurrences in text and count them


#1

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:


#2

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


#3

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
    }, {});

#4

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.