Home > Enterprise >  Find the difference between 2 values inside array
Find the difference between 2 values inside array

Time:04-05

I want to find the numeric difference between 2 values inside an object.

My objects are done like this:

{ today: 9, lastMonth: 6 }

I'm inside an every() method:

const validation = Object.values(myObj).every(item => console.log(item))

The every method is inside a reduce() method, because i have an array of object like the one i write up here.

Right now item log is printing value without any connection to the previous object, but one by one, so seems that i can't do a difference between the value like so:

function difference(a, b) {
  return Math.abs(a - b);
}

What i expect:

(item => difference(item))

to find the difference between the 2 values present in my object

What is happening:

Difference is returning NaN because item are not taken together

Edit: I fixed the main problem, now i have a simple array like so:

[[0,2],[4,9],[5,7]]...

seems that Math.abs(a-b) doesn't work with array, there is a valid solution to this?

CodePudding user response:

If you use the spread syntax (...) as you call the difference function the result should be as expected.

I'd suggest creating a wrapper getDifferences() function to implement this:

function difference(a, b) {
  return Math.abs(a - b);
}
   
function getDifferences(arr) {
  return arr.map(el => difference(...Object.values(el)));
}

console.log(getDifferences([{ today: 9, lastMonth: 6 }]));
console.log(getDifferences([[0,2],[4,9],[5,7]]));
console.log(getDifferences([{ a: 1, b: 2 }, { x: 1, y: 3 }]));
.as-console-wrapper { max-height: 100% !important; }

You could also use function.apply, this will also allow you to pass an array of arguments to a function:

function difference(a, b) {
  return Math.abs(a - b);
}
   
function getDifferences(arr) {
  return arr.map(el => difference.apply(null, Object.values(el)));
}

console.log(getDifferences([{ today: 9, lastMonth: 6 }]));
console.log(getDifferences([[0,2],[4,9],[5,7]]));
console.log(getDifferences([{ a: 1, b: 2 }, { x: 1, y: 3 }]));
.as-console-wrapper { max-height: 100% !important; }

CodePudding user response:

Try

function difference(array) {
  var result = [];
  for(var i=0;i<array.length;i  ){
   result.push(Math.abs(array[i][0]-array[i][1]));
}
return result
}
var arr = [[0,2],[4,9],[5,7]]
console.log(difference(arr))

  • Related