Search code examples
javascriptarraysobject

How do I update an object within an array using findIndex?


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.


Solution

  • You can achieve this via array.foreach() , Object.keys() and map().

    Refer the below code for reference :

    function calculateFrequency(inputArray) {
      let frequencyMap = {};
    
      // Count the frequency of each term
      inputArray.forEach(term => {
        frequencyMap[term] = (frequencyMap[term] || 0) + 1;
      });
    
      // Convert the frequency map to an array of objects
      const termsArr = Object.keys(frequencyMap).map(term => {
        return { term, frequency: frequencyMap[term] };
      });
    
      return termsArr;
    }
    
    const inputArray = ["Apple", "Orange", "Banana", "Apple", "Pear", "Banana"];
    const result = calculateFrequency(inputArray);
    
    console.log(result);