nb_nb_nb
nb_nb_nb

Reputation: 1381

Calculate values in array of objects based on other values in array of objects

I have an array of objects like so:

    let data = [
    {date:'2020-05-01', device: 'iphone',   site: 'google', val1:10, val2:20, val3:30},
    {date:'2020-05-01', device: 'iphone',   site: 'bing',   val1:23, val2:12, val3:14},
    {date:'2020-05-01', device: 'iphone',   site: 'jeeves', val1:67, val2:78, val3:12},
    {date:'2020-05-03', device: 'iphone',   site: 'google', val1:10, val2:20, val3:30},
    {date:'2020-05-03', device: 'iphone',   site: 'bing',   val1:23, val2:12, val3:14},
    {date:'2020-05-03', device: 'iphone',   site: 'jeeves', val1:67, val2:78, val3:12}
    ];

I want to subtract the vals from 2020-05-03 with 2020-05-01when the site is the same and finally return something like:

    [
    {device: 'iphone',   site: 'google', val1:-5, val2:5, val3:15},
    {device: 'iphone',   site: 'bing',   val1:10, val2:-10, val3:53},
    {device: 'iphone',   site: 'jeeves', val1:10, val2:21, val3:13},
    ]

I tried to do a forEach but I am not really sure where to go from there and how to write a function to make this more reusable:

    
    data.forEach(d => {
        if (d.data === )
    });

Sorry, I really don't where to go from here which is why i really cant show what I tried.

Upvotes: 0

Views: 390

Answers (1)

M Umair
M Umair

Reputation: 227

You can use nested loops to achieve this. Loop through the same array inside your first loop and check if both objects have same site then subtract values. You can push the resultant object into another array and return that array.

    //in your case it will be like this:
    const SubtractValues = (data) => {
      let resultarr = [];  
      data.forEach(d => {
            data.forEach(d2 => {
              //if both objects have same site and they are not the same object
              if(d2.site == d.site && d != d2){
                let result = {device: d.device, site: d.site, val1: d2.val1 - d.val1, val2: d2.val2 - d.val2, val3: d2.val3 - d.val3}
                //if result with same site is not already present in the results array
                if(!(resultarr.some(item => item.site === result.site))){
                  resultarr.push(result)
                }
              }
            })
        });
      return resultarr;
    }

Upvotes: 1

Related Questions