Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i search inside array of array object in javascript?

I have a booking array of arrays that contain objects and I have to search inside the array using searchValue could you please help me here

here we have to check the booking id if booking id and searchValue matched we have to push that object into result array.

let bookingArr = [
  [{
      name: "user 1",
      bookingid: 10,
      product: "ab"
    },
    {
      name: "user 1",
      bookingid: 10,
      product: "cd"
    }
  ],
  [{
      name: "user 2",
      bookingid: 11,
      product: "ui"
    },
    {
      name: "user 1",
      bookingid: 10,
      product: "ef"
    }
  ],
  [{
      name: "user 3",
      bookingid: 12,
      product: "ui"
    },
    {
      name: "user 4",
      bookingid: 13,
      product: "ef"
    }
  ]
];


var searchValue = "10,11";

var FOUND = bookingArr.find(function(post, index) {
  if (post.bookingid == 11)
    return true;
});


console.log(FOUND)

expected result

[ { name:"user 1", bookingid:10, product: "ab" },
    { name:"user 1", bookingid:10, product: "cd" },
    { name:"user 1", bookingid:10, product: "ef" },
    { name:"user 2", bookingid:11, product: "ui" }]
like image 794
its me Avatar asked Mar 16 '26 19:03

its me


2 Answers

You can try this code:

const bookingArr = [[
  { name: 'user 1', bookingid: 10, product: 'ab' },
  { name: 'user 1', bookingid: 10, product: 'cd' },
], [
  { name: 'user 2', bookingid: 11, product: 'ui' },
  { name: 'user 1', bookingid: 10, product: 'ef' },
],
[
  { name: 'user 3', bookingid: 12, product: 'ui' },
  { name: 'user 4', bookingid: 13, product: 'ef' },
]];


const searchValue = '10,11';

const sv = searchValue.split(',').map(Number);

const FOUND = bookingArr.flat().filter(({ bookingid }) => sv.includes(bookingid));

console.log(FOUND);
like image 102
salkcid Avatar answered Mar 19 '26 08:03

salkcid


You can use Array#filter with a Set for better performance after flattening the array.

let bookingArr = [[
    { name:"user 1", bookingid:10, product: "ab" },
    { name:"user 1", bookingid:10, product: "cd" }
],[
    { name:"user 2", bookingid:11, product: "ui" },
    { name:"user 1", bookingid:10, product: "ef" }
],
[
    { name:"user 3", bookingid:12, product: "ui" },
    { name:"user 4", bookingid:13, product: "ef" }
]];
let searchValue = "10,11";
let set = new Set(searchValue.split(",").map(Number)); // for faster lookup
let res = bookingArr.flat().filter(x => set.has(x.bookingid));
console.log(res);
like image 38
Unmitigated Avatar answered Mar 19 '26 10:03

Unmitigated