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

Angular animation not firing on exit

I am encountering an issue with my tooltip component's animations. The ":enter" animation is working as expected, but the ":leave" animation never seems to trigger. For reference, here is a link to stackblitz: https://stackblitz.com/edit/building-too ...

Exploring the world of functional programming in Java can be a rewarding experience, especially

I am seeking a method to define generic computation on a data set and have the compiler alert me if there are any errors. Having experience with TypeScript, I have seen that you can achieve something like this: /** * Type inferred as: * Array<{ * ...

Utilizing Core-TransitionEnd in Polymer: A Beginner's Guide

After a ripple animation on an item has executed, I would like to run a function. Currently, I am using the following code: <post-card id="card1"> <img width="70" height="70" src="../images/start.png"> <h2>P ...

Create a smooth transition: How to make a hidden button appear after a function finishes in JavaScript

I am completely new to the world of JavaScript, HTML, and CSS, so I'm feeling a bit lost on how to proceed with this task. My goal is to create a script that will initially display some text through a specific function. Once that text has been displa ...

Activate a click on a div element to enable smooth scrolling when using the page down and page up keys

Whenever I directly click on my div, the pageUp and pageDown keys scroll the contents of the div. But when I trigger a click programmatically, the scrolling with pageUp and pageDown stops working. How can I enable scrolling with pageUp and pageDown without ...

What is the reason for XMLHttpRequest.status being equal to 0 in all browsers except for Internet Explorer?

I am encountering a frustrating issue... After developing a standalone RESTful.NET webservice using C#, I noticed that when I make a XMLHttpRequest to fetch JSON data, all browsers, except for IE, fail to retrieve the data. The problem lies in the status ...

Using the .show() function will not alter the outcome or trajectory

I am currently working with some divs in my project where I want to implement the JQuery functions .show() and .hide(). However, I have encountered an issue where I am unable to change the effects or directions of these animations. Here is a snippet of th ...

Using node-fetch version 3.0.0 with jest results in a SyntaxError stating that import statements cannot be used outside a module

Recently, I've been updating my API to utilize node-fetch 3.0.0. One major change highlighted in their documentation is that node-fetch is now a pure ESM module. Click here for more information on the changes This update caused some of my unit tests ...

Obtaining Relative Values within Every Iteration using jQuery

I'm currently facing an issue with retrieving relative values within a .each() loop using jQuery. I have a set of table rows that contain a text input and a radio button each. My objective is to iterate through each row and save the value of the text ...

What is the best way to maintain the correct 'this' context for a function that is outside of the Vue

I'm struggling with my Vue component and encountering some errors. <script lang="ts"> import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, va ...

Formatting decimals with dots in Angular using the decimal pipe

When using the Angular(4) decimal pipe, I noticed that dots are shown with numbers that have more than 4 digits. However, when the number has exactly 4 digits, the dot is not displayed. For example: <td>USD {{amount| number: '1.2-2'}} < ...

The error message "TextEncoder is not defined with mongodb nodes" is indicating that there is

Encountering an issue while running jest test cases: Getting the error message - ReferenceError: TextEncoder is not defined. Current Node version being used is 14.18.0. Mongodb NPM package version is 4.1.3. Typescript version installed is 4.4.3. Here ...

The AngularJS templates' use of the ternary operator

Is there a way to implement a ternary operation in AngularJS templates? I am looking for a way to apply conditionals directly in HTML attributes such as classes and styles, without having to create a separate function in the controller. Any suggestions wo ...

Can you explain the true meaning behind this specific type definition?

Since starting to dive into TypeScript recently, I came across an express server written in TS while browsing the Internet. However, I am struggling to comprehend the type definition of the 'middlewares' argument. Despite attempting to research i ...

Electron's Express.js server waits for MongoDB to be ready before executing queries

As I work on a demo application, Express serves some React code that interacts with a MongoDB database hosted on mLab. The data is retrieved using SuperAgent calls in my main React code loaded via index.html. While everything works fine when starting the ...

Is there a way to create an interpolated string using a negative lookahead condition?

When analyzing my code for imports, I will specifically be searching for imports that do not end with -v3. Here are some examples: @ui/components <- this will match @ui/components/forms/field <- this will match @ui/components-v3 ...

Find with user-friendly input/label removal function (Ionic 2)

I have embarked on creating a recipe application where users can search for recipes by ingredients. I want to enhance the functionality of the search feature so that when users press the spacebar to enter the next input, it appears as a label below with an ...

Is there a way to prompt text typing actions to circumvent verification on an application?

As I explore ways to streamline my interactions on Whatsapp web, I am experimenting with a javascript shortcut. Specifically, I am creating predefined messages for quick responses to my contacts. To execute this task, I load the whatsapp page and inject jq ...

An error is displayed when attempting to construct an express-react application

Currently, I am working on a project in React and ExpressJS that was previously worked on by someone else. When attempting to run the command npm run build An error is displayed in the project: https://i.stack.imgur.com/PsfpS.png How can I resolve thi ...

What factors influence Redux in determining when to update the user interface?

As per the design, when the state updates, the UI should also update accordingly. However, if I return a completely new object, it seems to have no effect on the UI. case 'clearArticleForm': let newState1 = {}; return newState1; } E ...