I have example of javascript array as below.
var exampleArr1 = [5,4,1,-2,-5,-7,5,1,2,-3,2,4...];
var exampleArr2 = [-5,-4,1,2,5,7,-5,1,2,3,-2,4...];
I would to create function to detect sign change and return with position, e.g. ['index','num1','num2'] For example.
function getSignChange(exampleArr1){
...
return someArray;
}
return shoud be
[
[2,1,-2], //index = 2 change from 1 to -2
[5,-7,5], //index = 5 change from -7 to 5
[8,2,-3], //index = 8 change from 2 to -3
]
Any advice or guidance on this would be greatly appreciated, Thanks.
Maybe this will help you:
var exampleArr1 = [5,4,1,-2,-5,-7,5,1,2,-3,2,4];
var exampleArr2 = [-5,-4,1,2,5,7,-5,1,2,3,-2,4];
function getSignChange(arr){
let positive = arr[0] >= 0;
return arr.map((item, index) => {
if (positive && item < 0 || !positive && item >= 0) {
positive = arr[index] >= 0
return [index-1, arr[index-1], item]
}
}).filter(x => x != null);
}
console.log(getSignChange(exampleArr1));
console.log(getSignChange(exampleArr2));