Nina S Nina S - 5 months ago 9
Javascript Question

Filter array and get first values as array of object for unique id

I've the following array
I need to return only the uniqe ID for example since in this array I have
twice id 1 & 3 I need new array with just the first findigs id,

In this example the first 3 entries, how I can use it with maps/filter and not with regular for

var oData = [{
id: 1,
ListTypeGroupDescription: 2,
test: 111,
test2: 222
}, {
id: 2,
ListTypeGroupDescription: 4,
test: 333,
test2: 444
}, {
id: 3,
ListTypeGroupDescription: 6,
test: 666,
test2: 777
}, {
id:1,
ListTypeGroupDescription: 99,
test: 666,
test2: 777
}, {
id: 3,
ListTypeGroupDescription: 99,
test: 666,
test2: 777
}];


var data = oData.map(
function(obj) {
return obj.id;
}
);


http://jsfiddle.net/5qu0j8g0/1/

The map is returning only the ID's but I need the all objects

I need this newArray

var oNew = [{
id: 1,
ListTypeGroupDescription: 2,
test: 111,
test2: 222
}, {
id: 2,
ListTypeGroupDescription: 4,
test: 333,
test2: 444
}, {
id: 3,
ListTypeGroupDescription: 6,
test: 666,
test2: 777
}
]

Answer

You could filter it with Array#filter and a temporary hash table Object.create(null)) (a really empty object without any prototypes), inside the callback addressed with this.

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var oData = [{ id: 1, ListTypeGroupDescription: 2, test: 111, test2: 222 }, { id: 2, ListTypeGroupDescription: 4, test: 333, test2: 444 }, { id: 3, ListTypeGroupDescription: 6, test: 666, test2: 777 }, { id: 1, ListTypeGroupDescription: 99, test: 666, test2: 777 }, { id: 3, ListTypeGroupDescription: 99, test: 666, test2: 777 }],
    oNew = oData.filter(function (a) {
        if (!this[a.id]) {
            this[a.id] = true;
            return true;
        }
    }, Object.create(null));

console.log(oNew);