Home » Javascript » Remove items in node.js array that start the same

Remove items in node.js array that start the same

Posted by: admin November 1, 2017 Leave a comment

Questions:

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%" ]
Answers:

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)