skip to Main Content

This is my array.
I want to get the sub-arrays where the first element is "admin".

const array = [["admin", 1234], ["user", 999], ["admin", 5555]];

The expected output should look like this:

[admin,1234], [admin,5555]

2

Answers


  1. You can just use the filter() function. In the callback function you can use destructuring to get the first element of the sub-array, and compare that element to the value "admin":

    const array = [["admin", 1234], ["user", 999], ["admin", 5555]];
    
    const result = array.filter(([k]) => k === 'admin');
    
    console.log(result);
    Login or Signup to reply.
  2. We can use the filter method to check if the value of the first index of the subarray is "admin."

    Here is the proposed solution:

    const array = [["admin", 1234], ["user", 999], ["admin", 5555]];
    const filteredArray = array.filter(subArr => subArr[0] == "admin");
    
    console.log(filteredArray , ' <<---------- filteredArray');
    

    Additionally, if the subarray is unordered
    then we can look for the value "admin" and filter out the subarray.

    const array = [["admin", 1234], ["user", 999], ["admin", 5555]];
    const filteredArray = array.filter(subArr => (subArr.includes("admin") === true);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search