skip to Main Content

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

Answers


  1. 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);
    Login or Signup to reply.
  2. 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));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search