-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

3
  • type object array - there's no such type. Elaborate your desired structure. Do you want an array of objects? Commented Sep 11, 2017 at 10:39
  • Yes. I want to convert into array object. Commented Sep 11, 2017 at 10:48
  • Fruits [0] should contains fname as apple and count as 2 Commented Sep 11, 2017 at 10:49

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

Thanks you . It's working for me
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})  
}

Comments

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);
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.