-2

I have an array for example

var Fruits : ["apple","banana","apple", "orange","banana","kiwi","orange"];

Now I want to get the count with removing duplicate values in below type object array

0: fname: "apple"
    Count: 2;
1: fname: "banana"
    Count: 2;
2: fname: "orange"
    Count: 2;
3:fname: "kiwi"
    Count: 1;

Can anyone help me to get this object array

adiga
  • 34,372
  • 9
  • 61
  • 83

4 Answers4

0

var Fruits = ["apple","banana","apple", "orange","banana","kiwi","orange"];

var uniqueArr = Fruits.filter(function(elem, index, self) {
    return index == self.indexOf(elem);
})

var resObjArr = [];

uniqueArr.forEach(function(ele){
  var count = 0;
  var resObj = {};
  Fruits.forEach(function(eleF){
    if(ele == eleF) count++;
  })
  resObj['fname'] = ele;
  resObj['Count'] = count;
  resObjArr.push(resObj);
})

console.log(resObjArr)

Remove duplicates from your array. and count distinct element in your main array how many times it present. Then push it to result object.

Durga
  • 15,263
  • 2
  • 28
  • 52
0

Short Array.prototype.reduce() approach:

var fruits = ["apple","banana","apple", "orange","banana","kiwi","orange"],
    result = [];
 
fruits.reduce(function(r, i){
    (r[i])? r[i].count += 1 : result.push((r[i] = {fname: i, count: 1}));  
    return r;
}, {});
 
console.log(result);
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0
arr = []
for(var i = 0; i < Fruits.length; i++){
    if (arr.indexOf(Fruits[i]) == -1){
        arr.push(Fruits[i])    
    }
}

objects = []

for (var a = 0; a < arr.length; a++){
    var count = Fruits.filter(function(fruit) fruit == arr[a])
    objects.push({"fname": arr[a], "count": count.length})  
}
Quartal
  • 410
  • 3
  • 14
0
var Fruits = ["apple","banana","apple", "orange","banana","kiwi","orange"];

var uniqueArr = new Set(Fruits);
var result = [];
uniqueArr.forEach(function(ele){
  var count = 0;
  var resObj = {};
   Fruits.forEach(function(eleF){
       if(ele == eleF)
      count++;

  })
  resObj['fname'] = ele;
  resObj['Count'] = count;
  result.push(resObj);
})
praveen
  • 11
  • 5