Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make an array A with the result of each value of array B splitted by pipe

I have an array of strings. Some of the strings within this array have a pipe character. I would like to split the strings by "|" and store all the unique values into a new array.

What would be an efficient way to get a temporary array with all the splited values in it, without using poor performance loops?

Once I have the temporary array with all the splited values in it, I plan de remove all duplicates like this :
var result = […new Set(result)]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var arr = ["A|B|C","B|A","E|A|D","F"]

// result does not have to be sorted
var expectedResult = ["A","B","C","D","E","F"]

>Solution :

Use flatMap() and split() to get a single array, and use a Set to retain unique elements:

const array = ["A|B|C","B|A","E|A|D","F"];
const result = [...new Set(array.flatMap(v => v.split('|')))];

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading