0

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().

4
  • 2
    Since id is an array you can't use b.id === 56. Use another array method like includes to make sure the id is in the array. Commented Jun 28, 2023 at 13:55
  • const peopleFinder = id => people.find(e=>e.id.includes(id))?.name; will be fine...(?) Commented Jun 28, 2023 at 14:13
  • check my Array::reduce() solution, seems faster Commented Jun 28, 2023 at 14:40
  • 1
    does it allows to find several names? for example id 34 has 2 names Commented Jun 28, 2023 at 14:54

5 Answers 5

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 !

1
  • 1
    Answers (even those that work) should not just be code. You should explain what the problem was and how your code solves it. Commented Jun 28, 2023 at 13:55
1

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);

0

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;
  });
0
0

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))

5
  • { id.includes(idToFind) && result.push(name); return result; } could be id.includes(idToFind) ? [...result, name] : result
    – JollyJoker
    Commented Jun 28, 2023 at 15:35
  • @JollyJoker could be but performance will suffer significantly because of the array copying Commented Jun 28, 2023 at 15:42
  • I like your seeking for performance improvements yet I think, sometimes its just better to write straight forward code that everyone can comprehense easily instead of overcomplicating things for an array of length 3.
    – Behemoth
    Commented Jun 28, 2023 at 23:28
  • @Behemoth folks should do better than es5. legacy js is buggy. programmers should learn modern version of languages Commented Jun 29, 2023 at 0:34
  • @Behemoth using var is a crime nowadays Commented Jun 29, 2023 at 0:35
0

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 );

Not the answer you're looking for? Browse other questions tagged or ask your own question.