menu

Questions & Answers

Array's elements in JavaScript
  • What am I trying to do: Given an array of numbers, for example: ["1", "2", "1", "1", "2", "2", "3"], I want to find the element that is most repeated in the array. But, I also want to know if there is more than 1 element that satisfies the requirement, and what are those elements.

  • I couldn't think of any idea on how to start with this yet...

Comments:
2023-01-23 23:10:10
See Get the element with the highest occurrence in an array. Get familiar with how to access and process objects, arrays, or JSON, and use the static and instance methods of Object and Array. Also, what you’re looking for is called the mode.
Answers(1) :

This is an approach using Array.reduce()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

  • First I determine for each unique value in the array how many times it does occur, by returning an object like {"1": 3, "2": 3, "3": 1}
  • Then I determine which are the values occurred most of the times in the array, by returning an object like {"count": 3, "values": ["1", "2"]}

const data = ["1", "2", "1", "1", "2", "2", "3"];

//returns the number of time each unique value occurs in the array
const counts = data.reduce( (counts, item) => {
  if(item in counts)
    counts[item] += 1;
  else
    counts[item] = 1;
  return counts;
}, {});

console.log(counts);
/*
{
  "1": 3,
  "2": 3,
  "3": 1
}
*/

//returns which values and how many times occur the most 
const max = Object.entries(counts)
  .reduce((max, [value, count])=> {
      if(count < max.count)
        return max;
      if(count == max.count){
        max.values.push(value);
        return max;
      }
      return {count: count, values: [value]};
    },{count: 0, values: []});

console.log(max);
/*
{
  "count": 3,
  "values": [
    "1",
    "2"
  ]
}
*/

Comments:
2023-01-23 23:10:10
“But, I also want to know if there is more than 1 element that satisfies the requirement, and what are those elements.” — This doesn’t answer the question.
2023-01-23 23:10:10
@SebastianSimon My answer was worse than I thought compared to when it was already too late to delete it. Anyway I now better addressed the points that I was totally ignoring before.