Search code examples
javascriptarrayssortingstring-matchingarray-push

How might I return multiple arrays with equal values from a larger array with mixed values?


I have an array that after being sorted appears like this:

var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];


There are 2 "a" Strings, 4 "b" Strings, and 3 "c" Strings.

I am trying to return 3 separate arrays, returning them one at a time from a loop, containing only matching values. So, upon the first iteration, the returned array would appear as newArr = ["a", "a"],  the second as newArr = ["b", "b", "b", "b"]  and on the third iteration as newArr = ["c", "c", "c"].  

However, this is a small array of predefined values, and I need an algorithm that can perform the same operation on an array of unknown size, unknown elements, and with an unknown number of like elements. (and keep in mind that the array is already sorted to begin with, in this context)

Here's my crazy code that is displaying some unusual, and incorrect, results:

var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];

for(var index = 0; index < arr.length; index++)
{
  var test = "";
  var newArr = []; // resets the new array upon each iteration
  var str = arr[index]; // initialized as the next unique index-value

  for(var i = index; i < arr.length; i++)
  {
    if(arr[i] == str)
    {
      newArr.push(arr[k]);
      test += arr[i] + " ";
    }
    else
    {
      index = i; // changing the outer loop variable
      break; // exiting the inner loop
    }
  } // end of inner loop

  window.alert(test);
  setValues(newArr);

} // end of outer loop

function setValues(arrSorted)
{
  var here = document.getElementById("here");

  for(var i = 0; i < arrSorted.length; i++)
  {
    here.innerHTML += arrSorted[i] + "&nbsp;";
  }

  here.innerHTML += "<br />";

} // end of setValues function

Solution

  • var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
    var arrays = {};
    for (var i=0;i<arr.length;i++) {
      if (!arrays[arr[i]]) arrays[arr[i]] = [];
      arrays[arr[i]].push(arr[i]);
    }
    

    this will give you the equivalent of

    arrays = {};
    arrays['a'] = ['a','a'];
    arrays['b'] = ['b','b','b','b','b'];
    arrays['c'] = ['c','c','c'];