I am converting a longer array to a nested array of smaller arrays. For each array in the nested array, I want to perform some calculations taking the elements of the array, and push the result into the array.
//Split bigger array into smaller arrays....this function works
function getArray() {
items = ['image1','place','name',10,20,30,40,50,60,'image1','place','name',11,21,31,41,51,61];
img = "image1"
var size = 9;
var newarr = [];
for (var i = 0; i < items.length; i+=size) {
newarr.push(items.slice(i, i+size));
}
return newarr;
}
function fourthCoord(arr) {
for (var i = 0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
var newarr = arr;
firstx = newarr[j][3];
secondx = newarr[j][5];
var thirdd = secondx-firstx;
thirdx = newarr[j][7];
var fourthx = thirdx-thirdd
newarr.push(fourthx);
return newarr;
}
}
}
function init(){
var ctx = document.getElementById('canvas').getContext('2d');
ctx.canvas.addEventListener('click', function(event) {
var arr = new Array();
arr = fourthCoord(getArray(arr));
console.log(arr);
})
}
window.addEventListener('load', init, false);
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>array</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<canvas id="canvas" width="800" height="600" style="border:solid 1px;margin:0;padding:0;"></canvas>
</body>
</html>
The fourthCoord function pushes the resultant value outside the array as an element and not within each array.
[Array(9), Array(9), 30]
["image1", "place", "name", 10, 20, 30, 40, 50, 60]
["image1", "place", "name", 11, 21, 31, 41, 51, 61]
30
The desired output is:
[Array(9), Array(9)]
["image1", "place", "name", 10, 20, 30, 40, 50, 60, 30]
["image1", "place", "name", 11, 21, 31, 41, 51, 61, 30]