Created
June 13, 2014 21:05
-
-
Save darshilv/4bc57fee8fbb5e8bd80b to your computer and use it in GitHub Desktop.
An approach to get unique results from an array of objects having a duplicate value for a `key`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Object Array with duplicate data | |
var objArr = [{ | |
"name": "abc" | |
}, { | |
"name": "abc" | |
}, { | |
"name": "def" | |
}, { | |
"name": "def" | |
}, { | |
"name": "def" | |
}]; | |
//array that holds the value you want unique | |
function makeUnique(arr, key) { | |
var uniqueName = []; | |
var result = []; | |
objArr.map(function(e, i) { | |
if (uniqueName.indexOf(e[key]) == -1) { | |
uniqueName.push(e[key]); | |
result.push(e); | |
} | |
}) | |
return result; | |
} | |
console.log(makeUnique(objArr, "name")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment