Home > Net >  adding every 2 numbers of the array together. Jquery
adding every 2 numbers of the array together. Jquery

Time:12-22

I have a list like this:

myList = [1.32412694112, 1.2904242732, 0.59030181, 0.5741011728, 0.6093767538, 0.5832783666, 0.5674657211999999, 0.5775693444]

I want to reduce the length of myList by adding some of the items.

 myList = [2.61455121432, 1.1644029828, 1.1926551204, 1.14503506559]

CodePudding user response:

Here I've made a simple way to do it. There are more "clean" ways to do it, but I want to keep it simple so it's easier to learn from it.

var myList = [1.32412694112, 1.2904242732, 0.59030181, 0.5741011728, 0.6093767538, 0.5832783666, 0.5674657211999999, 0.5775693444];
var n = [];

for (var i = 0; i < myList.length; i  = 2) {
  n.push(myList[i]   myList[i   1]);
}

Demo

var myList = [1.32412694112, 1.2904242732, 0.59030181, 0.5741011728, 0.6093767538, 0.5832783666, 0.5674657211999999, 0.5775693444];
var n = [];

for (var i = 0; i < myList.length; i  = 2) {
  n.push(myList[i]   myList[i   1]);
}

console.log(n)

  • Related