Difference Between Two Adjacent Numbers In Array
I start my adventure with AngularJS and I have a question, is it possible to calculate the difference between two numbers? After extracting data from SQL - I get a table like this,
Solution 1:
I think its in the scope of simple javascript.
If you have your data in an array just use a simple iteration on it and compare the visit of current day to the visits from previous day.
A very simple solution might be:
var visitsArr = [38,29,18,29,28,18,24];
checkVisitsDiff(visitsArr);
functioncheckVisitsDiff(arr){
//Input validation check if(!arr || arr.length <2){
throw"Bad input!";
}
//If input is ok - Start from second elementfor(var i=1; i<arr.length; i++){
var currentElement = arr[i];
var previousElement = arr[i-1];
console.log("The difference from visit " + i + " to visit " +(i-1) + " is: " +(currentElement-previousElement));
}
}
I hope this what you asked.
Solution 2:
Use Array methods:
var visitsArr = [38,29,18,29,28,18,24];
var diffs = visitsArr.slice(1).map((x,i)=> x-visitsArr[i]);
diffs.forEach((x,i) =>console.log(
`Visits from day ${i+1} to day ${i+2} increased by ${x}`
));
For more information, see
Post a Comment for "Difference Between Two Adjacent Numbers In Array"