简体   繁体   中英

JavaScript - Filtering array with identical elements

I'm working on this code where I need to filter an array with multiple identical elements, which looks like this;

vacant = [
"A510.4 - 0h 45 m",
"A520.6 - 3h 0 m",
"A250.1 - 3h 0 m",
"A340.1 - 3h 15 m",
"A320.2 - 3h 0 m",
"A240.4 - 4h 0 m",
"A210.3 - 4h 0 m",
"A520.5 - 5h 0 m",
"A250.1 - 6h 0 m",
"A240.4 - 7h 0 m",
"A320.6 - 8h 0 m",
"A340.1 - 8h 0 m"]

The identical elements in the uniqueVacant - array are:

A250.1 - 3h 0 m / A250.1 - 6h 0 m

A340.1 - 3h 15 m / A340.1 - 8h 0 m

A240.4 - 4h 0 m / A240.4 - 7h 0 m

I have already filtered out the timestamp from the elements so the only thing needed is to compare the element names;

function getName(str) {
  return str.substring(0, str.indexOf('-'));
}

var uniqueVacant = [];
vacant.forEach(function (vacantStr) {
  uniqueVacant.push(getName(vacantStr))
});

The results should look like this, only leaving the first element with the same name and removing the second one which prints out later;

uniqueVacant = [
"A510.4 - 0h 45 m",
"A520.6 - 3h 0 m",
"A250.1 - 3h 0 m",
"A340.1 - 3h 15 m",
"A320.2 - 3h 0 m",
"A240.4 - 4h 0 m",
"A210.3 - 4h 0 m",
"A520.5 - 5h 0 m",
"A320.6 - 8h 0 m"]

// Removed A250.1 - 6h 0 m, A340.1 - 8h 0 m, A240.4 - 7h 0 m,

Note that when the timer is up for the elements, they get removed out from the array and after that the second element with the same name should appear back in the array, if there's no more similarities inside the array.

The similarities also varies from day to day, sometimes it's only 2 similar elements and other days it might be 8 or more.

Any quick and effective way to do this?

Try with Array#reduce

 var vacant = [ "A510.4 - 0h 45 m", "A520.6 - 3h 0 m", "A250.1 - 3h 0 m", "A340.1 - 3h 15 m", "A320.2 - 3h 0 m", "A240.4 - 4h 0 m", "A210.3 - 4h 0 m", "A520.5 - 5h 0 m", "A250.1 - 6h 0 m", "A240.4 - 7h 0 m", "A320.6 - 8h 0 m", "A340.1 - 8h 0 m" ] console.log(vacant.reduce((a, b) => { var k = a.map(a => a.split('-')[0]) if (!k.includes(b.split("-")[0])) { a.push(b) k.push(b.split("-")[0]) } return a; }, [])) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM