JinkyBu2
JinkyBu2

Reputation: 51

array help. How to multiply arrays by itself, without the first element in one, and without the last element in the other

my array from user input: [1,2,3,4]

what I want:

[1,2,3]*[2,3,4]
(1*2) + (2*3) + (3*4) = 20

what I have so far:

var array = [];
var number= document.getElementById("number").value; //this is where user inputs the number for my array

var sum = 0;
for (var i = 0; i< number.length; i++){
    array.push(parseInt(number[i]));
    var first= number[i-1];
    var second = number[i+1];
    sum += (first*second);
}
console.log(sum);

Upvotes: 3

Views: 112

Answers (3)

Get Off My Lawn
Get Off My Lawn

Reputation: 36341

You could use slice to get subsets of the arrays and then use reduce to create the sum like this:

const arr = [1,2,3,4]

const first = arr.slice(0, -1)
const last = arr.slice(1, arr.length)

const result = first.reduce((acc, num, idx) => acc + num * last[idx], 0)

console.log(result)

Upvotes: 0

Maxqueue
Maxqueue

Reputation: 2454

No need for an array for this.

In the following pattern: (1*2) + (2*3) + (3*4) you can see how this can occur using for loop without array.

Following works:

var number= parseInt(document.getElementById("number").value); //this is where user inputs the number for my array
var sum=0;
for (var i = 1; i< number; i++){
    sum += i*(i+1);
}
console.log(sum);

Upvotes: 1

user13198697
user13198697

Reputation:

that is my solution with reduce method of array

[1, 2, 3, 4].reduce((a, c, i, s) => (s[i + 1] ? c * s[i + 1] + a : a), 0);

Upvotes: 1

Related Questions