Home > Blockchain >  How can I turn all the objects founded in Arr.find into a big Array?
How can I turn all the objects founded in Arr.find into a big Array?

Time:12-11

I have this function: printRecords which receives an Array of IDs:numbers, and I have to find() and print (before sorting and doing other stuff) the user's object that matches the IDs given as arguments.
So I did the following:

function printRecords(recordIds) {
    for (const currId of recordIds) { 
     const person = studentRecords.find((student) => student.id == currId)
     const personArr = Array.of(person)
     console.log([...personArr])   
    }    
}

const currentEnrollment = [ 410, 105, 664, 375 ];

var studentRecords = [
    { id: 313, name: "Frank", paid: true, },
    { id: 410, name: "Suzy", paid: true, },
    { id: 709, name: "Brian", paid: false, },
    { id: 105, name: "Henry", paid: false, },
    { id: 502, name: "Mary", paid: true, },
    { id: 664, name: "Bob", paid: false, },
    { id: 250, name: "Peter", paid: true, },
    { id: 375, name: "Sarah", paid: true, },
    { id: 867, name: "Greg", paid: false, },
];

printRecords(currentEnrollment)

I already iterate the argument and found the users object that match ID but now the question is… How I turn it back into an object's array. I thought that Array.of()/ spread would have done it, but instead of taking the objects as a whole it works individually on every one.
the log is:

[ { id: 410, name: 'Suzy', paid: true } ]
[ { id: 105, name: 'Henry', paid: false } ]
[ { id: 664, name: 'Bob', paid: false } ]
[ { id: 375, name: 'Sarah', paid: true } ]

and I need:


[{ id: 410, name: 'Suzy', paid: true },
{ id: 105, name: 'Henry', paid: false },
{ id: 664, name: 'Bob', paid: false },
{ id: 375, name: 'Sarah', paid: true } ]

Thanks in advance.

CodePudding user response:

You can simplify the logic by using filter() and includes() to find the matches. This will already return the array you need without any further amendments:

function printRecords(recordIds) {
  let personArr = studentRecords.filter(record => recordIds.includes(record.id));
  console.log(personArr)
}

const currentEnrollment = [410, 105, 664, 375];
var studentRecords = [
    { id: 313, name: "Frank", paid: true, },
    { id: 410, name: "Suzy", paid: true, },
    { id: 709, name: "Brian", paid: false, },
    { id: 105, name: "Henry", paid: false, },
    { id: 502, name: "Mary", paid: true, },
    { id: 664, name: "Bob", paid: false, },
    { id: 250, name: "Peter", paid: true, },
    { id: 375, name: "Sarah", paid: true, },
    { id: 867, name: "Greg", paid: false, },
];

printRecords(currentEnrollment)

  • Related