Turn method ES6 find() to something in ES5

2.7k Views Asked by At

I need to join values of 2 arrays of objects and make a third one out of it. I use es6 method find() to make it but i've been asked some es5 code for this piece of logic. I wanted to use indexOf() but i dont know how to make it unfortunately...

thanks for your very kind help.

const caByEmployee = [{
        id: 8,
        period1: 652.40,
        period2: 3831.73,
        name: 'Tam'
    },
    {
        id: 18,
        period1: 421.95,
        period2: 1036.18,
        name: 'Nathalie'
    },
    {
        id: 20,
        period1: 300.5,
        period2: 1179.15,
        name: 'Liliane'
    }
]

const attendanceByEmployee = [{
         id : 1,
         period1 : 0,
         period2 : 86
    },
    {
         id : 8,
         period1 : 98,
         period2 : 520
    },
    {
         id : 18,
         period1 : 70,
         period2 : 49
    },
    {
         id : 20,
         period1 : 4,
         period2 : 227
    }
]

const averageCartByEmployee = caByEmployee.map(function (ca) {
    var attendance = attendanceByEmployee.find(function (attendance) {
        return attendance.id === ca.id;
    });

    return {
        id     : ca.id,
        name   : ca.name,
        period1: ca.period1 / attendance.period1 || 0,
        period2: ca.period2 / attendance.period2 || 0
    };
});

this give a result like so which is totally fine but not made with es5

[ { id: 8, 
    name: 'Tam', 
    period1: 6.657142857142857, 
    period2: 7.368711538461539 }, 
  { id: 18, 
    name: 'Nathalie', 
    period1: 6.027857142857143, 
    period2: 21.1465306122449 }, 
  { id: 20, 
    name: 'Liliane', 
    period1: 75.125, 
    period2: 5.194493392070485 } ] 
1

There are 1 best solutions below

0
On

Polyfilling find is trivial, see the link for one such polyfill but there are others out there.

You can't use indexOf because it looks for the thing actually in the array, and you want to match by id. (You could use findIndex, but it's also not an ES5 method.)

If you don't want to polyfill, you'll want a simple for loop, breaking when you find an entry with the matching id.