skip to Main Content
var people = [
    {name: 'John', id: [34, 44, 77]},
    {name: 'Jose', id: [43, 54, 65]},
    {name: 'Hanna', id: [56, 34, 98]}
];

var peopleFinder = people.filter(function(b){
    return b.id === 56;
}).map(function(n2){
    return n2.name;
})
console.log(peopleFinder);

How to print an name from an array of objects, by a given ID. This has to be solve without using any type of loops. Just array methods are allow to be use: .filter(), .map(), .reduce() and .find().

5

Answers


  1. However, since the id property in each object is an array, you need to use the .includes() method to check if the given ID exists within the array.
    Please check below code and try, i have made some changes:

    var people = [
      {name: 'John', id: [34, 44, 77]},
      {name: 'Jose', id: [43, 54, 65]},
      {name: 'Hanna', id: [56, 34, 98]}
    ];
    
    var peopleFinder = people.filter(function(person) {
      return person.id.includes(56);
    }).map(function(person) {
      return person.name;
    });
    
    console.log(peopleFinder);

    In this code, the filter() method is used to find the objects that have the ID 56 in their id array. The includes() method is used to perform the check. Then, the map() method is used to extract the name property from the filtered objects.

    Hope this will help !

    Login or Signup to reply.
  2. You’re almost there. Just make sure you check if the id array includes the id you’re looking for and don’t compare by value:

    var people = [
      {name: "John", id: [34, 44, 77]},
      {name: "Jose", id: [43, 54, 65]},
      {name: "Hanna", id: [56, 34, 98]}
    ];
    
    const id = 56;
    
    const name = people.filter(p => p.id.includes(id)).map(p => p.name);
    console.log(name);
    Login or Signup to reply.
  3. Well, first we need to filter out the ones that dont have the id we are searching for. For that we user filter().

    var peopleFinder = people
      .filter(function(person) {
        return person.id.includes(idToFind);
      })
    

    In more detail, what the filter function does is filters the array to only include the items that match out criteria.

    After that we have to map our user’s name, so we user the map() function.

      .map(function(person) {
        return person.name;
      });
    

    Then by putting them both together we should get the name of the person with the Id we need.

    var peopleFinder = people
      .filter(function(person) {
        return person.id.includes(idToFind);
      })
      .map(function(person) {
        return person.name;
      });
    
    Login or Signup to reply.
  4. An Array::reduce() compact version:

    const people = [
      {name: "John", id: [34, 44, 77]},
      {name: "Jose", id: [43, 54, 65]},
      {name: "Hanna", id: [56, 34, 98]}
    ];
    const idToFind = 34;
    console.log(people.reduce((result, {name, id}) => {
      id.includes(idToFind) && result.push(name);
      return result;
    }, []));

    And a benchmark:

    enter image description here

    <script benchmark data-count="1">
    
        const chunk = [
            { name: 'John', id: [34, 44, 77] },
            { name: 'Jose', id: [43, 54, 65] },
            { name: 'Hanna', id: [56, 34, 98] }
        ];
    
        let people = [];
    
        let count = 5000000;
        while (count--) {
            people.push(...chunk);
        }
    
        const idToFind = 34;
    
        // @benchmark Kedar's solution
        people.filter(function (person) {
            return person.id.includes(idToFind);
        }).map(function (person) {
            return person.name;
        });
    
    
        // @benchmark Alexander's solution
        people.reduce((result, { name, id }) => {
            id.includes(idToFind) && result.push(name);
            return result;
        }, []);
    
    
    </script>
    <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>

    Just for fun, don’t try to reproduce at home, a regex version 🙂

    var people = [
      {name: 'John', id: [34, 44, 77]},
      {name: 'Jose', id: [43, 54, 65]},
      {name: 'Hanna', id: [56, 34, 98]}
    ];
    
    const id = 34;
    const regex = new RegExp(`(?<=name":")[^"]+(?=","id":\[[\d,]*(?<=\D)${id})`, 'g');
    console.log(JSON.stringify(people).match(regex))
    Login or Signup to reply.
  5. You can use Array#find method as follows:

    const 
          people = [ {name: 'John', id: [34, 44, 77]}, {name: 'Jose', id: [43, 54, 65]}, {name: 'Hanna', id: [56, 34, 98]} ],
          
          id = 56,
          
          person = people.find(p => p.id.includes(id))?.name || 'not found';
          
    console.log( person );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search