In JavaScript how do I create a list of differences of array elements elegantly?

frans

I have a list of numbers, say numbers = [3,7,9,10] and I want to have a list containing the differences between neighbor elements - which has to have one less element - in the given case diffs = [4,2,1]

Of course I could create a new list go through the input list and compile my result manually.

I'm looking for an elegant/functional (not to say pythonic) way to do this. In Python you would write [j-i for i, j in zip(t[:-1], t[1:])] or use numpy for this.

Is there a reduce()/list comprehension approach in JavaScript, too?

Nina Scholz

You could slice and map the difference.

var numbers = [3, 7, 9, 10],
    result = numbers.slice(1).map((v, i) => v - numbers[i]);

console.log(result);

A reversed approach, with a later slicing.

var numbers = [3, 7, 9, 10],
    result = numbers.map((b, i, { [i - 1]: a }) => b - a).slice(1);

console.log(result);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to elegantly split array of strings in list elements by substring?

How do I sum the elements of an array list?

How do I show a of list elements of an array?

How do I return specific vector elements in c++ elegantly

How do I elegantly initialize an array of std::atomic?

How to create a numpy array filled with differences of elements of another array

How do I create a list with elements from 1 to N in prolog

How do i create an input that adds elements to an array?

how do i create a two list from a list inside of an array?

How do I create a javascript function that add html elements dynamically?

How do I remove all List elements from an Array?

How do I increment every element in an array list by n elements?

How to elegantly fill an array/list with values

How do I add new elements to an array using a promt in javascript?

How do I find out the number of elements in a Javascript array?

How do I iterate over properties of an array (not the elements) in javascript?

How do I add a string to all existing elements in array in javascript?

How do I access elements of an array in a property in Javascript object?

How do I Replace the elements in the Array and assign it zero in javascript?

How can I elegantly do not . any in Haskell?

How do I create a react list component from an array of objects?

F# how do I create an Array/List of Structs

In Excel how do I create a condensed list from another array?

How do i create array/list keys in python?

How do I create (d) elements arrays out of another array of (n > d) elements?

How do i create a JSON file from an array in JavaScript?

How do I create JavaScript array (JSON format) dynamically?

How do I create a javascript array of lists of objects?

How do I create and modify an associative array in JavaScript?