javascript - Duplicate-free version of array of objects -
i implemented function creates duplicate-free version of array, doesn't work array of objects. don't understand , can't find information how fix it.
my function:
function uniq(array) { var length = array.length; if (!length) { return; } var index = 0; var result = []; while (index < length) { var current = array[index]; if (result.indexof(current) < 0) { result.push(current); } index++; } return result; }
example:
var my_data = [ { "first_name":"bob", "last_name":"napkin" }, { "first_name":"billy", "last_name":"joe" }, { "first_name":"billy", "last_name":"joe", } ] uniq([1, 1, 2, 3]) // => [1, 2, 3] uniq(my_data) // => [ { "first_name":"bob", "last_name":"napkin" }, { "first_name":"billy", "last_name":"joe" }, { "first_name":"billy", "last_name":"joe" } ]
do know how creates duplicate-free version of array of objects?
indexof() in javascript not perform deep comparison of objects. on top of that, 2 objects created never "equal" each other. if do:
var = {}; var b = {}; == b; //false === b; //false
you need perform deep comparison against values (if that's you're looking do, because there other equalities you're looking for). won't go how deep comparison because, well, google.
Comments
Post a Comment