How can I loop through an array using underscore.js and access both the previous value and the current value in each iteration?

Is there a simple magical function combination from underscore (lo-dash) that can achieve the following algorithm:

var arr = [1, 4, 9, 16, 25];
var result = [];
for(var i = 1, len = arr.length; i < len; ++i) {
    var current = arr[i];
    var previous = arr[i-1];
    result[i-1] = current - previous;
}
// result == [3, 5, 7, 9]

with a more concise syntax:

var arr = [1, 4, 9, 16, 25];
var result = _.???(arr, function(current, previous) {
    return current - previous;
}

Can this be done with existing methods?

Additional Information:

  1. I prefer not to write my own function and would rather utilize combinations of existing functions.
  2. The arrays in question actually contain objects, not numbers, and the resulting output may or may not be numeric.

Answer №1

If you want to manipulate an array in JavaScript, you can use the _.map() method and access the index (i) and collection it provides.

var arr = [1, 4, 9, 16, 25];
var result = _.map(arr, function(curr, i, arr) {
    return i ? curr - arr[i-1] : null;
}).slice(1);

In this example, I have included a check to return null in the first iteration and then removed it using slice().

You can see it in action here


Alternatively, if you prefer, you can achieve a similar outcome using _.reduce(). By always returning the current item, you can extract the last and current items in the loop.

var arr = [1, 4, 9, 16, 25];
var result = [];
_.reduce(arr, function (last, curr) {
    result.push(curr - last);
    return curr;
});

Check out the implementation here

Answer №2

One alternative method I discovered is:

let array = [1, 4, 9, 16, 25];
_.map(_.zip(_.rest(array , 1), _.first(array, array.length - 1)), function(pair) {
    let currentNumber = pair[0];
    let previousNumber = pair[1];
    return currentNumber - previousNumber;
});

However, this approach has a time complexity of O(4n) (assuming that map, zip, rest, and first are linear operations) and it is quite verbose.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Run JavaScript code before finalizing the "submit" action within a Ruby on Rails application

Having trouble with utilizing old JS scripts found on Stack Overflow. <div class="form-actions"> <%= f.button :submit, class:"btn btn-success create-campaign" %> </div> The submit button is causing an issue for me. <div clas ...

Access to the requested URL has been restricted. Flask is unable to process the method

I have been working on creating a dynamic web service for user login. Utilizing JavaScript, jQuery, and HTML, I aim to make the login process seamless and efficient. However, I have encountered an issue where, upon entering the correct username and passwor ...

JavaScript and PHP are successfully displaying a success message despite the data not being saved to the database

I recently added a new feature to my website where users can submit a form using Javascript without having to reload or refresh the page. This allows for a seamless experience and displays success messages instantly. However, being a newcomer to Javascript ...

html css javascript, Is it possible to execute a script before a webpage finishes loading?

My current setup is similar to a lightbox feature, but I'm facing an issue where the script waits for the entire webpage to load before running. Is there a way to ensure that my script runs first without waiting for the webpage to fully load? CSS: # ...

Using Jquery to dynamically adjust the size of a div based on the width and height of the browser window

How can I dynamically change the height of a .test div based on the browser width and height? I want the value to update whenever the browser is resized. $(document).ready( function() { window.onresize = function(event) { resizeDiv(); ...

Establishing the default tab in JavaScript

Here's the JavaScript code snippet I have: jQuery(document).ready(function($) { // filtering subcategories var theFilter = $(".filter"); var containerFrame = $(theFilter).closest(".container-frame") var filterHeight = $(".filter").children("li") ...

There is no need for updates as git is already current for some mysterious reason

As a newcomer to git, I've been trying to wrap my head around it but still struggling. Can someone help clarify this for me? My question pertains to the 'master' branch in git which contains the following code: const list = [ 'h&ap ...

Searching for a specific value within a list that has been fetched from a database using AngularJs can be achieved by simply clicking on the search button

Seeking assistance on a search functionality issue. I am able to filter search results from a list retrieved from the database and displayed on an HTML page, but facing difficulty in getting complete search results from the controller. When clicking the se ...

Issues with Jquery Ajax POST request not resolving

Can you explain why the success code is not being executed in this request? $(document).ready(function(){ var post_data = []; $('.trade_window').load('signals.php?action=init'); setInterval(function(){ ...

What is the method to design a file upload feature without a specific form using JavaScript?

I am currently working on a form that handles file uploads using jQuery and AJAX. The goal is to upload the files individually as JSON containing base64 data. Rather than uploading all the images at once, I want each image to be treated as if it were in it ...

Nothing is being displayed on the screen via React

Initially, I used a function instead of a class, and the code was functioning up to a certain point. However, now it is not displaying anything at all. In my VehiclesList.js, I am generating 10 random vehicles. Here is the code snippet: import React from ...

Setting state back to default following the conditional rendering of a React component

Whenever the save button is clicked, I aim to display a snackbar component by updating the showSnackbar state to true. To achieve this in React, it's just a simple conditional check in the main render method. The snackbar I'm using here automatic ...

How can I expand all primary accordions while keeping secondary accordions collapsed?

I have a main accordion with nested accordions within each item. My goal is to only expand the main level accordions when clicking the button, without opening the nested ones. I want to open all "Groups" accordions while keeping the sub-accordions labeled ...

React Native - The Animated.spring function experiences a flickering issue when the animation is reverted

I am currently working on implementing a drawer in my react native app. The issue I am facing is with the closing animation. When I click the close button, the animation seems to blink or flicker, as if it is opening and closing multiple times before final ...

Enhancing a blog entry in Meteor.js

Recently, I embarked on a journey to learn Meteor.js in hopes of creating a newsfeed feature that allows me to add, edit, and delete content. As of now, I am facing challenges with the editing process. imports/api/news/methods.js Meteor.methods({ ...

The moment a connection is established, the link abruptly vanishes - NodeJS and MYSQL

Lately, I've been facing a persistent issue with my node application that suddenly started crashing every time a connection is established. This problem emerged out of nowhere after my application had been running smoothly for months. The crash occurr ...

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

Material UI - Array of Chips

I have been working on creating a ReactJS component that displays an array of chips with unique styling for each one. To achieve this, I created individual makeStyles classes for the chips. However, I encountered difficulties in dynamically changing the cl ...

ERROR: The data has reached its end prematurely (data length = 0, requested index = 4). Could this be a corrupted zip file?

Currently, I am developing a WhatsApp bot and storing the chat data in an Excel file using exceljs for further processing. In order to handle responses efficiently, I am utilizing promises to resolve them. Below is the function I have created to read the c ...

Add a class individually for each element when the mouse enters the event

How can I apply the (.fill) class to each child element when hovering over them individually? I tried writing this code in TypeScript and added a mouseenter event, but upon opening the file, the .fill class is already applied to all elements. Why is this ...