Skip to content Skip to sidebar Skip to footer

Grouping Js String Array With Counting

I have simple array in js var fruit = [ 'apple' , 'apple' , 'orange' ] I need this groped so that i can present data in format: apple 2 orange 1 I have tried with creating two a

Solution 1:

You can do this succinctly with with reduction:

functioncount(xs) {
  return xs.reduce(function(a,e) {
    return a[e] = ++a[e]||1, a;
  },{});
}

count(fruit); //=> {apple:2, orange:1}

Solution 2:

You can iterate though fruit value and increment a counter:

var result = {};
for (var i = 0, n = fruit.length; i < n; i++) {
  if (typeof result[fruit[i]] === 'undefined') {
    result[fruit[i]] = 1;
  } else {
    result[fruit[i]]++;
  }
}

console.log(result); // Object {apple: 2, orange: 1}

Solution 3:

This a way to do this:

var fruit = ['apple', 'apple', 'orange'];

var occurences = {};
for (var index = 0; index < fruit.length; index++) {
    var value = fruit[index];
    occurences[value] = occurences[value] ? occurences[value] + 1 : 1;
}

console.log(occurences);

The logged output is an object containing apple: 2, orange: 1} as you can see here: http://jsfiddle.net/zZ2hk/

Solution 4:

var fruits = [ 'apple' , 'apple' , 'orange' ];
var result = {};

for(var i = 0; i < fruits.length; i++){
    var item = fruits[i];
    result[item] = result[item] ? result[item] + 1 : 1;
}

console.log(result); // Object { apple=2,  orange=1}

Solution 5:

Try underscore countBy function:

var fruit = [ 'apple' , 'apple' , 'orange' ];
var count = _.countBy(fruit, function(el) {
    return el;
});

Also it has other very useful functions.

Post a Comment for "Grouping Js String Array With Counting"