javascript - lodash _.uniqWith performance hit -
i having real big performance hit _.uniqwith(newselectedmodellist, _.isequal);
.
i comparing array 2100 elements. each element has { name: 'foo', year: '1993'}
, { name: 'foo', year: '1993'}
, { name: 'foo', year: '2000'}
, removing duplicates have same name
, year
.
is there faster way this? or better tool lodash?
you use es6 filter
, set
. following function passes set
context (this
) callback:
function uniques(arr) { return arr.filter(function ({year, name}, key) { return !this.has(key = year + name) && this.add(key); }, new set()); } // sample data var newselectedmodellist = [ { name: 'foo', year: '1993'}, { name: 'foo', year: '1993'}, { name: 'foo', year: '2000'} ]; // output result console.log(uniques(newselectedmodellist));
in case want filtering happen in given variable, , not in new array returned function, suggest empty given array , repopulate it: faster longer arrays splice duplicates out, one-by-one:
function uniques(arr) { var res = arr.filter(function ({year, name}, key) { return !this.has(key = year + name) && this.add(key); }, new set()); // replace content in arr: arr.splice(0, arr.length, res); } // sample data var newselectedmodellist = [ { name: 'foo', year: '1993'}, { name: 'foo', year: '1993'}, { name: 'foo', year: '2000'} ]; // replace in-place: uniques(newselectedmodellist); // output result console.log(newselectedmodellist);
on js fiddle posted performance comparison solution guest271314 had posted @ time write this. on pc console output reports these measurements:
number of original elements: 30000 solution count duration ----------- ----- -------- trincot 14456 00020.14 guest271314 14456 00351.99
the count column gives number of unique elements retained in final result. number can change in different runs, input array bit of random. last column gives time used in milliseconds.
Comments
Post a Comment