How to implement a for nested in a for in a more modern ES6 way?

Someone asked me to solve this problem: Return only those objects whose property "enrollmentId" is in another number array: So I came up with this, and it works, however, I'm using a for inside a for, and I was wondering what's the best approach to this kind of problem. Please, check it out

const companions = [
  {name:"camila", enrollmentId:1},
  {name:"oscar", enrollmentId:2},
  {name:"rupertina", enrollmentId:3}
  
];

const participants = [7,2,4]

const finalResult = [];

for(i=0; i< companions.length; i++){
  
  let alumno = companions[i];
  
  for(j=0; j< participants.length; j++){
    
    let participante = participants[j];
    
    if(alumno.enrollmentId == participante){
      finalResult.push(alumno);
    }    
    
  }
}

console.log(finalResult)

Upvotes: 0

Views: 59

Answers (3)

Vanessa Torres
Vanessa Torres

Reputation: 46

If you want the ES6 way, go with code_monk code BUT imma up code_monk code, will all do respect (I cannot add a comment to his code as I am new to stack overflow and do not have enough reputation.) BUT an arrow function ( => ) does not need the keyword return nor the function budy {}, because it is implicit that a value will be returned after the =>

const companions = [
    {name:"camila", enrollmentId:1},
    {name:"oscar", enrollmentId:2},
    {name:"rupertina", enrollmentId:3}
];

const participants = [7,2,4];

const finalResult = companions.filter(companion => participants.includes(companion.enrollmentId));

console.log(finalResult);

Upvotes: 1

code_monk
code_monk

Reputation: 10128

I would use Array.filter to omit invalid rows, and Array.includes for the validity test

const companions = [
    {name:"camila", enrollmentId:1},
    {name:"oscar", enrollmentId:2},
    {name:"rupertina", enrollmentId:3}
];

const participants = [7,2,4];

const finalResult = companions.filter(companion => {
    return participants.includes(companion.enrollmentId);
});

console.log(finalResult);

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370879

Filter the original array by whether the enrollmentId of the object being iterated over is included in the participants.

const companions = [
  {name:"camila", enrollmentId:1},
  {name:"oscar", enrollmentId:2},
  {name:"rupertina", enrollmentId:3}
];
const participants = [7, 2, 4]

const finalResult = companions.filter(obj => participants.includes(obj.enrollmentId));
console.log(finalResult)

Upvotes: 2

Related Questions