Home > Software design >  How to filter array key by another array number key
How to filter array key by another array number key

Time:11-09

I have 2 array, first array structure is:

items: [
    {
      name: "a",
      items: [
         { name: "jack" },
         { name: "jose" },
      ]
    },
    {
      name: "b",
      items: [
         { name: "lara" },
         { name: "jo" },
      ]
    },
    {
      name: "c",
      items: [
         { name: "andy" },
         { name: "hary" },
      ]
    }
]

and the second array:

number: [
  0: [0, 1],
  1: [1],
  2: [0]
]

How to filter "items" by "number" and How can such an output be obtained? (the best solution)

{["jack", "jole"],["jo"],["andy"]}

CodePudding user response:

A few maps would do it:

the output you wish is not valid JS so I made a nested array

const arr1 = [{ name: "a", items: [{ name: "jack" }, { name: "jose" }, ] }, { name: "b", items: [{ name: "lara" }, { name: "jo" }, ] }, { name: "c", items: [{ name: "andy" }, { name: "hary" }, ] } ], numbers = [ [0, 1], [1], [0] ]; 

const res = numbers
  .map((arr, i) => arr
    .map(key => arr1[i].items[key].name)
  )
console.log(res)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

If your number variable has to be an Object.

let items = [
  {
    name: "a",
    items: [{ name: "jack" }, { name: "jose" }]
  },
  {
    name: "b",
    items: [{ name: "lara" }, { name: "jo" }]
  },
  {
    name: "c",
    items: [{ name: "andy" }, { name: "hary" }]
  }
];

let number = {
  0: [0, 1],
  1: [1],
  2: [0]
};

let result = []
for (const [key, value] of Object.entries(number)){
  let names = []
  value.forEach(value => {
    names.push(items[key].items[value].name)
  })
  result.push(names)
}

console.log(result)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related