Effortlessly apply mapping, filtering, reducing, and more in JavaScript

Array#map and Array#filter both create a new array, effectively iterating over the original array each time.

In languages like rust, python, java, c#, etc., such expression chains only iterate once, making them more efficient in certain cases.

While this may not be a concern in most scenarios, there are situations where the performance impact could be significant when using the function api of the Array class.

How do you address this issue? Do you have a preference for a library that enables lazy evaluation for functional expressions?

Answer №1

To prevent iterating more than once, consider using a loop

const numbers = [1,2,3,4,5,6]
let result = 0;
for(const number of numbers) {
  const square = number * number
  if(square % 2) {
    result += square
  }
}
console.log(result)

Alternatively, utilize the reduce method

const numbers = [1,2,3,4,5,6]
const result = numbers.reduce((acc, number) => {
  const square = number * number
  if(square % 2) {
    return acc + square
  }
  return acc
}, 0)
console.log(result)

It's important to note that array methods may not be purely functional due to their existence on the array object. However, you can approach this concept in a more functional manner

const square = (n) => n * n
const oddNumberOrZero = (n) => n % 2 ? n : 0
const add = (a, b) => a + b
const addOddSquare = (a, b) => add(a, oddNumberOrZero(square(b)))
const reduce = (arr, fn, acc) => arr.reduce(fn,acc)
const numbers = [1,2,3,4,5,6]

const result = reduce(numbers, addOddSquare, 0)

console.log(result)

Remember, fluent interfaces and functional programming are distinct concepts.

Answer №2

If you're interested in handling arrays as a stream, one option is to use the highland library:

import _ from "highland";
_([5, 6, 7, 8])
    .filter(v => v % 2 === 0)
    .map(v => v * 3)
    .toArray((result: number[]) => {
        // The transformed array is stored in the result variable
    });

You can find more information about this feature in the highland documentation:

When working with Arrays, each value will be emitted sequentially as part of the stream.

Answer №3

To access the stream-list library, simply install it via npm

https://www.npmjs.com/package/stream-list

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
 const myList = new List(numbers);
 myList
  .filter((number) => number % 2 == 0)  // only even numbers
  .map((number) => number * number)  // square
  .map((number) => number/2) // divide by half
  .toList(); // numbers list iterated only once

Answer №4

Please review the code snippet below to understand how the variable 'v' is being handled.

const numbers = [1,2,3,4,5,6];
const result = numbers.reduce((sum, v) => sum + (v % 2 ? v * v : 0), 0);
console.log(result);

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

Retrieve data with a web API

I am currently developing a web API to fetch data from a mock database using express My goal is to retrieve a JSON list containing all portfolios and their corresponding positions from the database module. Is there a way to structure the returned data so ...

Converting a timestamp from PHP in JSON format to date and time using JavaScript

Within the JSON file, there is a timestamp associated with each user login. An example of this timestamp is: timestamp: "1541404800" What steps should be taken to convert this timestamp into date and time format? ...

Should the element be scrolled beyond a fixed-positioned element

Is there a way to determine if an element is scrolled behind another element that is fixed at the top? I am looking to trigger some javascript when an element is positioned below a fixed element and every height or scrollTop thereafter. I am attempting t ...

Error encountered: EPERM when attempting to rename a directory in Node.js unexpectedly

There is a requirement for me to remove the Backup folder, rename the processor as Backup, create a Processor folder again, and send a response to the user. The code I am using for this task is as follows: fsExtra.remove('app/Backup', function(e ...

Updates made in the type declaration files are not being displayed

I'm currently working on an express app and I have been trying to add a new property to the Request's class instance. To achieve this, I created a type.d.ts file at the root of my project that looks like this: type User = { name: string } de ...

Adding a specific element to an array using JQuery

I am in the process of developing a web application using jQuery to track goals and habits. Users can set a main goal such as 'Discipline' and then add sub-goals or habits related to that main goal (e.g. 'exercise every day'). Organizi ...

Is there a way to prevent the window.on('beforeUnload') event from triggering when using the <a> tag?

For my project, I require a user confirmation alert to appear when the user attempts to close the window or tab using the X button. However, the window.on('beforeUnload') function also triggers for hyperlinks. How can I prevent the leave page al ...

Create independent SVG files using Meteor and iron-router

My goal is to use Meteor and Iron-Router to serve dynamic SVG files with templating capabilities. To start, I create a new route: @route 'svg', { path: '/svg/:name' data: -> { name: this.params.name } # sample data layoutT ...

Tips on obtaining the element's ID as a function parameter

I am currently learning front-end development and I am just starting to delve into JavaScript. Recently, when I tried to execute a piece of JavaScript code from the backend by passing some element ids, I encountered an error that says Cannot read property ...

Steps to Hide a Material-UI FilledInput

Trying to format a FilledInput Material-ui component to show currency using the following package: https://www.npmjs.com/package/react-currency-format Various attempts have been made, but none seem to be successful. A codesandbox showcasing the issue has ...

Merge two distinct arrays of objects based on a shared field

I have two arrays of objects that I need to merge, with the expected output as: [ { "scenario": [ { "errorname": "Error 01", "status": 5, "desc_1" : "test", "desc_2" : "testing" }, ...

Using ajax to call the Google Maps Api is proving to be ineffective

I am facing some issues with a website. On this particular webpage (), I am trying to display a Google map on the location page using an AJAX function. The getLocation.php file is being called by AJAX: <?php echo '<div id="map-canvas"></ ...

Leverage Custom_Pipe within TS

I am currently working with a pipe that I have created. Here is the code: @Pipe({ name: 'searchNomES' }) export class SearchNomESPipe implements PipeTransform { transform(uos: IUo[], name?: string,): IUo[] { if (!uos) return []; if (!name) ret ...

Invoke a Python function from JavaScript

As I ask this question, I acknowledge that it may have been asked many times before. If I missed the answers due to my ignorance, I apologize. I have a hosting plan that restricts me from installing Django, which provided a convenient way to set up a REST ...

Angular - Is there a specific type for the @HostListener event that listens for scrolling on the window?

Encountering certain errors here: 'e.target' is possibly 'null'. Property 'scrollingElement' does not exist on type 'EventTarget'. What should be the designated type for the event parameter in the function onWindow ...

Using the tensorflow library with vite

Greetings and apologies for any inconvenience caused by my relatively trivial inquiries. I am currently navigating the introductory stages of delving into front-end development. Presently, I have initiated a hello-world vite app, which came to life throug ...

Guide to interacting with the Li element using JavaScript in Selenium

Is there a way to click on the item inside the li element using a Selenium script with JavaScript? I've tried different methods like By.cssSelector or by css, but I keep getting an ElementClickInterceptedError: element click intercepted:Other element ...

My goal is to have the "show more" button reveal extra information without having to reload the entire page

I’m trying to figure out how to make the “more” button show additional information without reloading the entire page. I’ve done some research online and found that AJAX can help with this, but since I’m just starting to learn JavaScript, I have n ...

Acquire information from a Card using Oracle Apex

I have a Card Regions that showcases some of my tables. I'd like each card to redirect to a specific page based on a number (the "page_table" number corresponds to the page it will redirect to). Below is the Query for the Cards Region: SELECT table_n ...

Is there a way to trigger a function from a specific div element and showcase the JSON data it retrieves in

I am working with a React JS code page that looks like this: import React, { useState } from "react"; import { Auth, API } from "aws-amplify"; function dailyFiles(props) { const [apiError502, setApiError502] = useState(false); // Extracted into a re ...