Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Javascript array unique by attribute

What is a fast way of making a Javascript array unique by attribute?

I have an array sorted by timestamp, like this:

[
    {
        ts: 1417048100,
        release: 1.0
    },
    {
        ts: 1417046900,
        release: 1.1
    },
    {
        ts: 1417046712,
        release: 1.0
    }
]

And I want to make it unique by release number, keeping only the ones with the latest timestamp. In my example, that would mean removing the last entry since there is a newer one for that release.

like image 614
Daniel Larsson Avatar asked Dec 07 '25 22:12

Daniel Larsson


2 Answers

You could iterate over the array with forEach and store the release numbers in an object to make sure that any releases already iterated over are spliced out of the array.

var arr = [{
    ts: 1417048100,
    release: 1.0
},
{
    ts: 1417046900,
    release: 1.1
},
{
    ts: 1417046712,
    release: 1.0
}];

var o = {};

arr.forEach(function(x, i) {
    if (x.release in o) arr.splice(i, 1);
    o[x.release] = null; 
});

document.body.innerHTML = '<pre>' + JSON.stringify(arr, null, 4) + '</pre>';
like image 119
adeneo Avatar answered Dec 09 '25 14:12

adeneo


Convert it to a mapping, using the release as the key.

var output = {};
for(var i=0; i<input.length; i++) {
  output[input[i].release] = input[i].ts;
}

It will automatically overwrite older release keys with newer release keys.

If you need it to remain sorted, then you would need to re-convert it to a list and sort it, or filter the original list down by only the remaining output keys.

like image 27
gahooa Avatar answered Dec 09 '25 13:12

gahooa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!