All the current solutions assume that the numbers will be XXXX-Y where Y is always a number between 0 and 9 (maybe it is the requirement, but it is not clear in the question). In this case, we are working with Strings, so 1234-15 will be lower than 1234-7. It is needed to sort the Arraysin a numeric way. If we use the next Array with the current solutions on the page, this will be the 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 has been dropped because, as String, it is bigger than 14670-10 and 14670-20.
Here you have a solution that orders the Array first, and next reduce the values to get the lower ones (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 another solution is 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) );