A Dev A Dev - 2 months ago 5
Javascript Question

Javascript create array of unique objects from object

I have an elasticsearch response ($scope.myval) that conatins 100 records of user details. Of these 100 records, I need a list of just the user names and a few other fields, of which I know that there are only 5 unique records.

What I am trying to do is create a new array of only unique objects.

var meta = [];

function checkExists (value){
for (k = 0; k < meta.length ; k++){
if( meta[k].LoginName == value.LoginName){
console.log("matches")
}
else{
meta.push({
LoginName: value.LoginName,
});
}
}
}

for (j = 0; j <$scope.myval.length ; j++){
checkExists($scope.myval[j]._source)
}

console.log(meta);


However this doesn't appear to be working as meta is empty.

Any thoughts?

Answer

I would suggest editing your code so that "CheckExists" does exactly that, and if it doesn't exist, explicitly add it.

function checkExists (value){
    for (k = 0; k < meta.length ; k++){
        if( meta[k].LoginName == value.LoginName){
            console.log("matches")
            valueExists = true;
        }
    }
}

if (!valueExits){
     meta.push({
        LoginName: value.LoginName,
    });
}