0

I have an array like this

let names = [
    {name:"Haruhiro", alias:["Haru", "Hal"]},
    {name:"John", alias:["Jon"]},
    {name:"Samantha", alias:["Sam"]},
]

And I need to filter the items of it based on what the user types in.

let output = names.filter((e) => e.name === userInput);

This works well with only names, but I couldn't do it so that it fill check for both name and possible alias, since it can have as many alias as it wants I need to loop throuh it but I'm already in a sort of loop while I'm in the filter. I tried something like

let output = names.filter((e) => e.name === userInput || e.alias.filter((a) => a === userInput));

but it wouldn't work. So There's an array in an array that I'm looping through which I need to loop through

2 Answers 2

1

You should loop over the nested array with some which returns true/false, instead of filter which returns an array of elements(always true).

let names = [
  {name:"Haruhiro", alias:["Haru", "Hal"]},
  {name:"John", alias:["Jon"]},
  {name:"Samantha", alias:["Sam"]},
];

const result = names.filter(person => person.name === "no" || person.alias.some(alias => alias === 'Hal'));
console.log(result);

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but doesn't it stop after finding 1 that fits "Hal". I need to filter out every "Hal" if there were to be multiple
oh no I think I get it, it could work. It should work. I'll try it out
0

Since your allias arrray you can use the includes method on it to see if it has the value in it you want to check for so your code will be this:

let names = [{
    name: "Haruhiro",
    alias: ["Haru", "Hal"]
  },
  {
    name: "John",
    alias: ["Jon", "Hal"]
  },
  {
    name: "Samantha",
    alias: ["Sam"]
  },
]
let userInput = 'Hal'

let output = names.filter((e) => e.name === userInput || e.alias.includes(userInput));
console.log(output)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.