I have an array that has certain values and I am doing some calculation with it.
Here is my array check out the result:
var arr2 = [1,2,2,3] var newArr = [["a",0,1,2,0,223],["b",1,0,0,0,0],["c",0,0,0,0,223],["d",0,1,2,0,223]] const result = newArr.reduce((results, element, index) => { return [...results, // push the rest of the results onto the new array [...element, // keep all the current items of the element (the 1d array) Math.round(element[element.length-1]-(element[element.length-1]/(element[element.length-3]+element[element.length-4])*arr2[index])) // add new element, by querying the last element of the array and the appropriate index of the second array ] ] },[]); console.log(result)
It works fine until my divisor becomes 0. In the above code (element[element.length-3]+element[element.length-4])
sometime results 0 which gives NaN or infinity in array which I don't want instead it can throw zero.
Is there a way that I can use if condition inside it? Or any other solution?
You can treat the 0 value as false; when that happens you can set the divisor as 1.
((element[element.length-3]+element[element.length-4]) || 1)
The other option is to do the calculation in a separate variable.
var arr2 = [1,2,2,3] var newArr = [["a",0,1,2,0,223],["b",1,0,0,0,0],["c",0,0,0,0,223],["d",0,1,2,0,223]] const result = newArr.reduce((results, element, index) => { const aValue = element[element.length-1] const bValue = element[element.length-3] + element[element.length-4] const value = aValue?= 0 && bValue:= 0. aValue/bValue. 0 return [.,.results. // push the rest of the results onto the new array [.,.element. // keep all the current items of the element (the 1d array) Math,round(element[element;length-1]-(value*arr2[index])) ] ] }.[]); console.log(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.