Need an array where with first element of new array=sum of all elements except the first element-Javascript [closed]

StackOverflow https://stackoverflow.com/questions/20918947

  •  24-09-2022
  •  | 
  •  

Pregunta

I have an array arr[0,1,2,3,..10] in Java script.I need to make a new array with first element of new array=sum of all elements except the first element of the previous array,and goes on.

Description: I have

  Array=new Arr[0,1,2,3,..10].

I need an

  Array=new new Array[first element,second element..]

where

 first element=(1+2+..10)-0 ,
    second element=(0+2+3+..10)-1,
    third element=(0+1+3+..10)-2,

.. goes on till last element.
¿Fue útil?

Solución

var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var sum = myArray.reduce(function(previous, current) {
    return previous + current;
}, 0);
var newArray = myArray.map(function(currentElement) {
    return sum - currentElement;
});
console.log(newArray);

Output

[ 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45 ]

Otros consejos

Algorithm goes like this

  1. Just calculate the sum of all elements in the array
  2. Traverse the array and reduce the element value from the sum and push into new array

Code

var sum = 0;
var result = [];
for (var i = 0; i < arr.length; i++) {
  sum += arr[i];
}

for (var i = 0; i < arr.length; i++) {
  result.push(sum - arr[i]);
}

console.log(result);

Note that, this can be done with short snippets of code as well using a combination of Array.reduce and Array.every, Array.slice. But these all methods have browser compatibility issues as they are not supported in older IE browsers.

It looks like you'll have to do something like this:

var nums = new Array(0,1,2,3,4,5,6,7,8,9,10);
var sum = Function('return ' + nums.join('+') + ';')();
var final = [];

for(j = 0; j < nums.length; j++){
   final.push(sum - (2 * nums[j]) );
}

console.log(final);

The reason you have to do (2 * nums[i]) in the last step is:

  1. To get rid of the item from the original addition (the 2 in the line below - from your code),

  2. To subtract it at the end of the line.

var third element=(0+1+3+..10)-2,

fiddle - Cred to @wared for the sum function -

You can do this:

arr = [0,1,2,3,4,5,6,7,8,9,10]

//Sum them all
sum = 0
for(i=0; i<arr.length; i++){
   sum+=arr[i];
}

//Calculate the result
result = []
for(i=0; i<arr.length; i++){
   result.push(sum-arr[i]);
}

alert(result);

Check this fiddle: http://jsfiddle.net/eg7F6/

This is the generic approach:

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var sum = array.reduce(function (sum, value) { return sum+= value });
var newArray = array.map(function(value) { return sum - value });

However, if the array has always values from 0 to 10, you could do some shortcut – but at this point, I do not understand the point of having that.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top