All current solutions assume that the numbers will be XXXX-Y , where Y always a number between 0 and 9 (perhaps this is a requirement, but it is not clear in the question). In this case, we work with Strings , so 1234-15 will be below 1234-7 . You need to sort Arrays digitally. If we use the following Array with the current solutions on the page, these will be the following results:
var array = ["14670-20", "7851", "7851-2", "14670-10", "7851-1", "2234", "2235", "2235-1", "14670-7"]; // ["14670-20", "7851", "14670-10", "7851-1", "2235"] // ["14670-10", "14670-20", "7851", "7851-1", "2235"] // ["2235", "7851", "7851-1", "14670-10", "14670-20"]
The number 14670-7 was dropped because it is greater than 14670-10 and 14670-20 as a String .
Here you have a solution that first orders Array and then decreases the values ββto get lower (this solution changes the order of the original Array )
var array = ["14670-20", "7851", "7851-2", "14670-10", "7851-1", "2234", "2235", "2235-1", "14670-7"]; function getFilteredArray (array) { var reg = /^(\d+)\-?(\d*)$/; var current = ""; var sort = function (a, b) { var ra = a.match(reg), rb = b.match(reg); if (ra[1] === rb[1]) { return (+ra[2]) - (+rb[2]); } return (+ra[1]) - (+rb[1]); } return array.sort(sort).reduce(function (bundle, item, index) { var number = item.split("-")[0]; bundle.splice((current !== number) ? -1 : bundle.length, 1, item); current = number; return bundle; }, []).slice(0, -1); } console.log( getFilteredArray(array) );
This is another solution a little longer, but it keeps the order of the original Array :
var array = ["14670-20", "7851", "7851-2", "14670-10", "7851-1", "2234", "2235", "2235-1", "14670-7"]; function getFilteredArray (array) { var reg = /^(\d+)\-?(\d*)$/; var sort = function (a, b) { var ra = a.match(reg), rb = b.match(reg); if (ra[1] === rb[1]) { return (+ra[2]) - (+rb[2]); } return (+ra[1]) - (+rb[1]); } var objs = array.reduce(function (bundle, item) { var number = item.split("-")[0]; bundle[number] = bundle[number] || []; bundle[number].push(item); return bundle; }, {}); for (var prop in objs) { var last = objs[prop].sort(sort).pop(); array.splice(array.indexOf(last), 1); } return array; } console.log( getFilteredArray(array) );
source share