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)]
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"]
CodePudding user response:
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);
CodePudding user response:
.join('|')
array as a string with pipes between all letters, then .split('|')
by the pipe and then remove dupes with Set()
let data = ["A|B|C", "B|A", "E|A|D", "F"];
console.log([...new Set(data.join('|').split('|'))]);
CodePudding user response:
I would go with
const result = arr.map(item => item.split("|")).flat();
const deduped = [...new Set(result)]
CodePudding user response:
One more option:
const inputArray = ["A|B|C","B|A","E|A|D","F"];
const result = inputArray.reduce((acc, value) => acc.push(...value.split('|')) && acc, []);
console.log(result);
CodePudding user response:
const splitSet = (arr) => {
const set = new Set();
for(const item of arr) {
const splited = item.split("|");
for(const piece of splited) {
set.add(piece);
}
}
return Array.from(set);
}
splitSet(arr); //result
CodePudding user response:
The first thing that comes to my mind is this
const arr = ["A|B|C","B|A","E|A|D","F"];
const flatArr = arr.join('|').split('|');
const expectedResult = [...new Set(flatArr)];