methuselah
methuselah

Reputation: 13206

Manipulating arrays in JavaScript to remove repeat objects and total them up

How would I take the following array in JavaScript

locationList = [{
  id: 1,
  title: "Loughborough"
}, {
  id: 5,
  title: "Corby"
}, {
  id: 2,
  title: "Derby"
}, {
  id: 2,
  title: "Derby"
}, {
  id: 2,
  title: "Derby"
}];

and convert it into something like this:

locationList = [{
  id: 1
  title: "Loughborough",
  count: 1
}, {
  id: 5
  title: "Corby",
  count: 1
}, {
  id: 2
  title: "Derby",
  count: 3
}];

wherein all the titles are totalled up.

Upvotes: 0

Views: 56

Answers (3)

Derlin
Derlin

Reputation: 9881

One of many solutions:

var newl = [];
locationList.forEach(function(o) {
  if (newl[o.id] == undefined) {
    o.count = 1;
    newl[o.id] = o;
  } else {
    newl[o.id].count += 1;
  }
});

// if you want a trimmed array (with length = 3)
var trimedArray = newl.filter(function(n){ return n != undefined }); 

Upvotes: 4

Zhafur
Zhafur

Reputation: 1624

Loop through the elements, create a new array, put an element into the new array if the element is not yet in.

Edit: Otherwise, if it exists, just add 1 to the count in the new array, and then use the new array instead of the old.

Upvotes: 2

thatOneGuy
thatOneGuy

Reputation: 10622

As I have said in comments :

Create new array, loop through each element, if element.title is not in new array, add to array, if it is add to count in specific index

Upvotes: 1

Related Questions