Giox Giox - 17 days ago 8
jQuery Question

Remove an object with a single occurrence from an array

I'm trying to solve this small issue with an elegant solution without making nested loops or several temporary arrays...

I have an array of object dynamically generated from data coming from an API with several properties.
I'd like to remove from the array the object where a particular property is present only once.

myarray.push({code:'A', value:1423});
myarray.push({code:'A', value:5497});
myarray.push({code:'F', value:7986});
myarray.push({code:'CC', value:8456});
myarray.push({code:'CC', value:4897});
myarray.push({code:'CC', value:3216});
myarray.push({code:'B', value:4973});
myarray.push({code:'A', value:6189});
myarray.push({code:'B', value:5164});


So from the above array, I'd like to remove only the elements where code is F
The array dimension will be no more than 20~30 elements

I use only jQuery as external lib, and I need support for IE9 and above

Answer

If you know what code to filter out

You use filter. Filter takes a function that should return true or false. In this function, you check if code !== F.

var myarray = [];
myarray.push({code:'A', value:1423});
myarray.push({code:'A', value:5497});
myarray.push({code:'F', value:7986});
myarray.push({code:'CC', value:8456});
myarray.push({code:'CC', value:4897});
myarray.push({code:'CC', value:3216});
myarray.push({code:'B', value:4973});
myarray.push({code:'A', value:6189});
myarray.push({code:'B', value:5164});

var filteredArray = myarray.filter(function(item) {
  return item.code !== "F";
});

console.log(filteredArray);

If you don't know which codes appear only once

You have to count the occurrences first:

var myarray = [];
myarray.push({code:'A', value:1423});
myarray.push({code:'A', value:5497});
myarray.push({code:'F', value:7986});
myarray.push({code:'CC', value:8456});
myarray.push({code:'CC', value:4897});
myarray.push({code:'CC', value:3216});
myarray.push({code:'B', value:4973});
myarray.push({code:'A', value:6189});
myarray.push({code:'B', value:5164});


var counts = myarray.reduce(function(map, item) {
  map[item.code] = map[item.code] || 0;
  map[item.code] += 1;
  return map;
}, {});

var filteredArray = myarray.filter(function(item) {
  return counts[item.code] > 1;
});

console.log(filteredArray);