javascript - Sort array in ascending order while eleminating repeated values -
i'm working on project have array simmilar this
var sortbp = [ 'height58em', 'width480px', 'width768px', 'width959px', 'width767px', 'width767px' ];
i want sort array in ascending order while eleminating repeated values result should
var sortbp = [ 'height58em', 'width480px', 'width767px', 'width768px', 'width959px' ];
i'm using following function sort array in ascending array how eliminate immediate values ?? (in above case 'width767px')
var sortbp = bparrays.sort(function(a, b) { = a.replace(/[a-z]/g, ''); b = b.replace(/[a-z]/g, ''); return - b; });
firstly, can't eliminate elements while sorting. have sort array first, remove duplicates. solution using array.prototype.filter
, array.prototype.indexof
might unsorted array, since array sorted, it's overhead here(takes o(n)
each). instead can loop through array , compare element previous one.
function uniq(array) { var i, l = array.length, result = []; (i = 0; < l; i++) { if (result[result.length - 1] != array[i]) { result.push(array[i]); } } return result; }
this same underscore , prototype's uniq() implemention.
last note: remember work fine sorted array only.
Comments
Post a Comment