I have an array of strings. I want to loop through this array and create a new array that houses each string and the frequency it appears. So, if the string appears more than once the frequency
value in the new array gets updated.
From an array that looks like:
let strArr = ["Apple", "Orange", "Banana", "Apple", "Pear", "Banana"];
The desired result would be:
termsArr = [
{term: "Apple", frequency: 2},
{term: "Orange", frequency: 1},
{term: "Banana", frequency: 2},
{term: "Pear", frequency: 1}
]
I am trying to use findIndex()
to check if the termsArr
has a matching term in it already (and if yes update the frequency value), but it is failing saying term
is not defined. I don’t know why this is.
My full code:
let strArr = ["Apple", "Orange", "Banana", "Apple", "Pear", "Banana"];
let termsArr = [];
for (let i = 0; i < strArr.length; i++) {
let arrItem = strArr[i];
let objIndex = termsArr.findIndex((obj => obj.term == arrItem));
if (objIndex > 0) {
termsArr[objIndex].frequency = termsArr[objIndex].frequency + 1;
}
else {
termsArr[i] = {
term: arrItem,
frequency: 1
};
}
}
Would anyone know what I’m doing wrong here?
I thought it might be failing initially because the termsArr
is empty, so modified it as such:
let objIndex = 0;
if (i < 1) {
objIndex = termsArr.findIndex((obj => obj.term == arrItem));
}
But that did not make any difference.
3
Answers
You should use
strArr
instead oftextArr
to assign the value forarrItem
.Also change
objIndex > 0
toobjIndex !== -1
to correctly check if the term is not found in thetermsArr
.I will also suggest you to use
===
for the comparison inobj => obj.term === arrItem
for strict equality.You should check for
objIndex >= 0
instead ofobjIndex > 0
to include the case when the element is found at the first index.Your let strArr = should be textArr = and that will solve it. You are referencing an undefined textArr variable