I’ve found a solution that gives the correct result when the word is at the same index, within each of the array elements, but in the case below, the term/word searched can be anywhere in the element (beginning or end).
array = [ ["A"], ["earth"], ["20"], ["tunnel"], ["house"], ["earth A"], ["$100"], ["house $100"] ]
Expected result:
result = [ ["A", 2], ["earth", 2], ["20", 1], ["tunnel", 1], ["house", 2], ["earth A", 1], ["$100", 2], ["house $100", 1], ]
Here’s the attempt using the solution above:
array = [ ["A"], ["earth"], ["20"], ["tunnel"], ["house"], ["earth A"], ["$100"], ["house $100"] ]; function count(array) { return array.reduce((acc, arr) => { for (const item of arr) { acc[item] = acc[item] !== undefined ? acc[item] + 1 : 1 } return acc }, {}) } console.log(count(array))
Appreciate your help!
Advertisement
Answer
So: basically the same as Louys Patrice Bessette’s answer but instead of setting the value of the object prop to the current count it assigns an array (word and count) to the value instead, and then updates the count at index 1. Wrapping the operation in Object.values
will return only those arrays (as an array).
const data=[["A"],["earth"],["20"],["tunnel"],["house"],["earth A"],["$100"],["house $100"]]; const out = Object.values(data .flat() .join(' ') .split(' ') .reduce((acc, word) => { acc[word] ??= [ word, 0 ]; ++acc[word][1]; return acc; }, {}) ); console.log(JSON.stringify(out));
Additional documentation