Search code examples
javascriptarrayssumexcept

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


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.

Solution

  • 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 ]