[Solved] Find the infamous element in the array


You can start by iterating over the array and count the number of times each element occurs. Since you want the first instance of the least common value, you’ll also need to store the index the first time the value occurs since you can’t depend on the order they’re inserted into the object as objects aren’t ordered.

Then find the least common value with the lowest index, e.g.

var data = [4,4,4,4,1,4,4,2,4,4];

var values = data.reduce(function (acc, value, i) {
  if (!acc.hasOwnProperty(value)) {
    acc[value] = {count: 0, index: i};
  }
  acc[value].count++;
  return acc;
}, {});

console.log('Collated values:\n' + JSON.stringify(values));

var result = Object.keys(values).reduce(function(acc, value) {
  var obj = values[value];
  if (obj.count <= acc.count && obj.index < acc.index ) {
    acc = {value: value, count: obj.count, index: obj.index};
  }
  return acc;
}, {value: null, count: Infinity, index: Infinity});

console.log('Result:\n' + JSON.stringify(result));

solved Find the infamous element in the array