user2035174
user2035174

Reputation: 133

Remove items in node.js array that start the same

I have an array with the following values. I use this for an SQL search

var arr = ["ann%", "annie%", "aine%", "pat%", "annabelle%","patrick%" ]

I want remove values that that will be duplicated in the SQL. In this example "annie%" and "annabelle%" and "patrick%" results will be found with "ann%" and "pat%" searches so they are not required.

I need some node.js code that will return an array like this from the original.

var arr1 = ["ann%", "aine%", "pat%" ]

Upvotes: 0

Views: 67

Answers (1)

Mark
Mark

Reputation: 92450

You can use filter() and some() with something like this -- making sure not to filter out exact matches:

var arr = ["ann%", "annie%", "aine%", "pat%", "annabelle%","patrick%" ]

arr2 = arr.filter(testEl => !arr.some(item => item !== testEl && testEl.startsWith(item.replace('%',''))))
console.log(arr2)

Upvotes: 1

Related Questions