2

How can I create an array of indexes of the most common value of an array (empty strings should be excluded). My array is always of size three, which should simplify the problem but I have yet to find a way to solve this. I'm using JavaScript (ES5), so no access to Set.

E.g. the following would all return an empty array (consider " " as an empty string):

[" ", " ", " "] => []
["a", " ", " "] => []
[" ", "b", " "] => []
[" ", " ", "c"] => []
["a", "b", " "] => []
[" ", "b", "c"] => []
["a", " ", "c"] => []
["a", "b", "c"] => []

and the following would return:

["a", "a", " "] => [0, 1]
["a", "a", "c"] => [0, 1]
[" ", "b", "b"] => [1, 2]
["a", "b", "b"] => [1, 2]
["c", " ", "c"] => [0, 2]
["c", "b", "c"] => [0, 2]
["c", "c", "c"] => [0, 1, 2]
Gabriel
  • 342
  • 4
  • 12

2 Answers2

3

You can use reduce function and filter function

//["c", "b", "c"] => [0, 2]
var arr = ["c", "b", "c"];

function a(arr) {

  var result = arr.reduce(function(acc, cur, index) {
    if(cur == ' ' || cur == '') return acc; // skip if value - empty string
    if (!acc.map[cur]) { // if new value
      acc.map[cur] = [index]; // add index to map
      acc.result.push(acc.map[cur]);//add index to result array
    } else {
      acc.map[cur].push(index); // push index to result array
    }
    return acc;
  }, {
    map: {}, 
    result: []
  }).result.filter(function(el){ // get arrays only with length greater than 1
    return el.length > 1;
    })
  .reduce(function(acc, cur) { // get array with max length
    return acc.length > cur.length ? acc : cur;
  },[]);
  document.getElementById('r').innerHTML += JSON.stringify(arr) + ' => ' + JSON.stringify(result) + '<br />';
}

a([" ", " ", " "]);
a(["a", " ", " "]);
a([" ", "b", " "]);
a([" ", " ", "c"]);
a(["a", "b", " "]);
a([" ", "b", "c"]);
a(["a", " ", "c"]);
a(["a", "b", "c"]);

a(["a", "a", " "]);
a(["a", "a", "c"]);
a([" ", "b", "b"]);
a(["a", "b", "b"]);
a(["c", " ", "c"]);
a(["c", "b", "c"]);
a(["c", "c", "c"]);
<div id='r'></div>
Grundy
  • 13,356
  • 3
  • 35
  • 55
0

This works:

function myFunc(arr){
       var copy = arr.slice(0), val, j;
       var buffer = [];

       for(i=0; i<3; i++){
          val = arr[i]; 
          if(val == '' || val == ' '){
             continue;  
          }else{
             delete copy[i];
             if((j = copy.indexOf(val)) != -1){
                if(buffer.indexOf(i) == -1) buffer.push(i);
                buffer.push(j);
             }
          }
       }

       document.body.innerHTML = JSON.stringify(arr) + ' => ' + JSON.stringify(buffer);
      
       return buffer;
    }

myFunc(["c", "a", "a"]);
abeyaz
  • 3,034
  • 1
  • 16
  • 20