简体   繁体   中英

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)]

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"]

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);

.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('|'))]);

I would go with

const result = arr.map(item => item.split("|")).flat();
const deduped = [...new Set(result)]

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);

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

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)];

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