jquery - javascript sort and remap array -




i'm using following code (courtesy of jquery javascript sort array highest count) sort list of strings highest lowest count:

var items = {}, sortableitems = [], i, len, element, listofstrings;       listofstrings = json.parse(the_chems);   (i = 0, len = listofstrings.length; < len; += 1)      {         if (items.hasownproperty(listofstrings[i])) {             items[listofstrings[i]] += 1;         } else {             items[listofstrings[i]] = 1;         }     }  (element in items)      {         if (items.hasownproperty(element)) {             sortableitems.push([element, items[element]]);         }     }  sortableitems.sort(function (first, second)      {         return second[1] - first[1];     }); 

instead of type of array input

["red", "red", "red", "blue", "blue"] 

which returns

[ [ "red", 3 ], [ "blue", 2 ] ] 

i use array

[["red","apple"], ["red","chilli"], ["red","melon"], ["blue","ocean"], ["blue","eyes"]] 

and return

[["red", 3, ["apple","chilli","melon"]], ["blue", 2, ["blue","ocean"]] 

you use hash table , collect result in array.

var array = [["red", "apple"], ["red", "chilli"], ["red", "melon"], ["blue", "ocean"], ["blue", "eyes"]],      hash = object.create(null),      result = [];    array.foreach(function (a) {      if (!hash[a[0]]) {          hash[a[0]] = [a[0], 0, []];          result.push(hash[a[0]]);      }      hash[a[0]][1]++;      hash[a[0]][2].push(a[1]);  });    console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -