Sort Splitted words Respectively to another splitted words

34 Views Asked by At

I am trying to sort some words that i provide with another splitted words the input i give is

a = "excel|side|home|door" b = "|" c = "or|de|el"

and the code i am using is as

data.result = a.split(b)?.filter(x=>c.split(b).some(y => x.includes(y))).join(b);

that gives the output as excel|side|door which is respective/order as ‘a’ input but i want it ti return b as a order of ‘a’ instead of returning excel|side|door i want it to return as el|de|or.

2

There are 2 best solutions below

0
Unmitigated On

You can use flatMap to combine filter and map here. In addition, use Array#find to get the actual matching element rather than just checking for existence.

let a = "excel|side|home|door", b = "|", c = "or|de|el";
let res = a.split(b)?.flatMap(x=>c.split(b).find(y => x.includes(y))||[]).join(b)
console.log(res);

0
mochaccino On

Sort by the index they are found in a:

let a = "excel|side|home|door", b = "|", c = "or|de|el";

console.log(c.split(b).sort((x, y) => a.indexOf(x) - a.indexOf(y)).join(b));