Search code examples
javascriptarraysnode.jsobjectjavascript-objects

Compare two objects and extract the ones that have same Key in javascript


I have the following two objects

var productionTime= [
    {Rob3: 20},
    {Rob8: 100},
    {Rob4: 500},
    {Rob1: 100},
    {Rob5: 500}
];
var Busytime= [
    {Rob4: 10},
    {Rob3: 200},
    {Rob8: 100},
    {Rob5: 200},
    {Rob1: 100}
];

Now I want to divide each item in 'productionTime' by its respective 'BusyTime' which have the same key. For example productionTime.Rob3 should be divided by BusyTime.Rob3 and productionTime.Rob8 should be divided by BusyTime.Rob8 and so on.

How can I do this with array.find() or array.filter() in javascript/nodejs?

P.S: I know i can do it by using two nested forEach loops but that is I guess very slow


Solution

  • You could use a hash table and a single loop for every array.

    var productionTime = [{ Rob3: 20 }, { Rob8: 100 }, { Rob4: 500 }, { Rob1: 100 }, { Rob5: 500 }];
        busytime = [{ Rob4: 10 }, { Rob3: 200 }, { Rob8: 100 }, { Rob5: 200 }, { Rob1: 100 }],
        hash = Object.create(null);
    
    busytime.forEach(function (o) {
        var key = Object.keys(o)[0];
        hash[key] = o[key];
    });
    
    productionTime.forEach(function (o) {
        var key = Object.keys(o)[0];
        o[key] /= hash[key];
    });
    
    console.log(productionTime);
    .as-console-wrapper { max-height: 100% !important; top: 0; }