I have the following array:
0: {element: 'came', frequency: 3}
1: {element: 'here', frequency: 2}
2: {element: 'i', frequency: 1}
Each element is an object that shows the frequency of words in a text.
I want to do something like "The most frequent word was X, for Y times. The second most frequent word was Z, for D times.
So i did this. textObj is the array with the objects.
function Result() {
const results = [];
if (textObj.length != 0) {
for (let i = 0; i < textObj.length; i = 2) {
results.push(
<div>
<h1>Most frequent word was:</h1>
<h2>
'{textObj[i].element}' for {textObj[i].frequency} times
</h2>
<h1>Second most frequent word was:</h1>
<h2>
'{textObj[i ].element}' for {textObj[i ].frequency} times
</h2>
</div>
);
}
return results;
}
return <div></div>;
}
And then i render it returning in the main component.
In the above example, i have the phrase "I came came came here here". For some reason, it's showing only the word "came" in both . But the frequency part is correct, it's showing 3 and then 2. I tried instead of textObj[i ], textObj[i 1], but it says that cannot read 'element'.
What am i doing wrong?
CodePudding user response:
You have two problems. One of them is i
which you have addressed already. i
assigns i
a new value (of i 1
) and as it is postfix notation (in contrast to prefix notation i
) this value is only assigned after it is used, that explains why the word came
is shown twice and the frequency part is correct. But as you increment the value again in textObj[i ].frequency
you update i
once more.
Don't update i
, just use i 1
and it should work.
Now one other problem is when you use i 1
you will run out of bounds of the array when i = textObj.length - 1
, that's why it says cannot read 'element'
. To avoid this you have to change your condition in the for loop to let i = 0; i < textObj.length - 1; i = 2
.
CodePudding user response:
Most frequently used word and second most frequently used word can be done by sorting the array and getting the first and second elements
var arr = [{element: 'came', frequency: 3},
{element: 'here', frequency: 2},
{element: 'i', frequency: 1}]
var sortedArr = arr.sort((a, b) => b.frequency - a.frequency);
var mostFrequencWord = sortedArr[0];
var mostSecondFrequencWord = sortedArr[1];
console.log(`The most frequent word was ${mostFrequencWord.element}, for ${mostFrequencWord.frequency} time: `)
console.log(`The most frequent second word was ${mostSecondFrequencWord.element}, for ${mostSecondFrequencWord.frequency} time: `)