Basic use of javascript array includes and reduce

Basic use of javascript array includes and reduce

Preface

The JavaScript language has undergone several updates over the past few years. In order to keep up with the pace of technological updates, always keep a learning attitude. Take advantage of the break time to learn and familiarize yourself with the use of array includes and reduce.

Array.prototype.includes

ES7 adds support for this method. The includes() method is used to determine whether an array contains an element with a specified value and returns a Boolean value of true or false. If it is included, it returns true, otherwise it returns false.

grammar

arr.includes(valueToFind[, fromIndex])

parameter

  • valueToFind (required): The element value to be found. String and character comparisons are case-sensitive.
  • fromIndex (optional): Start searching for valueToFind from the array index fromIndex.
    • If it is a negative number, the search starts at the index of array.length + fromIndex in ascending order (that is, starting from the end, jumping forward by the absolute value of fromIndex, and then searching backward).
    • The default value is 0.

Return Value

Returns true if contained, false otherwise.

Examples

// ES5 Code
const numbers = ["one", "two", "three", "four"];
console.log(numbers.indexOf("一") > -1); // true
console.log(numbers.indexOf("六") > -1); // false

// ES7 Code
console.log(numbers.includes("一")); // true
console.log(numbers.includes("六")); // false

console.log(numbers.includes("一",1)); // false, search from array index 1 backwardsconsole.log(numbers.includes("一", -3)); // true, search from array.length + fromIndex backwards, equivalent to starting from index 1 above

Using the includes method can make the code short and easy to understand. The include method is also convenient for comparing values, as shown in the following code.

// past const day = "Tuesday";
if (day === "Tuesday" || day === "Wednesday" || day === "Thursday") {
    console.log(day);
}

// Nowif (["Tuesday", "Wednesday", "Thursday"].includes(day)) {
    console.log(day);
}

Array.prototype.reduce

The reduce() method executes the reducer function on each element in the array (in ascending order), summarizing the results into a single return value.

grammar

Array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

Executes the callback function for each element in the array in turn, excluding elements in the array that have been deleted or have never been assigned a value.

parameter

  • callback (required): Execute the reducer function for each value in the array (except the first value if initialValue is not provided), containing four parameters
    • accumulator (required): The accumulator accumulates the return value of the callback; it is the accumulated value returned when the callback was last called. The initial value can be defined by initialValue, which defaults to the first element value of the array. The accumulator will retain the value of the previous operation, just like a static variable.
    • currentValue (required): The element in the array being processed
    • index (optional): The index of the current element being processed in the array. If initialValue is provided, the starting index is 0, otherwise it starts at index 1.
      Note: If initialValue is not provided, reduce will start executing the callback method from index 1, skipping the first index. If initialValue is provided, start at index 0.
    • array (optional): the array to call reduce() on
  • initialValue (optional): The value that is used as the first argument when the callback function is first called. If no initial value is provided, the first element in the array will be used. Calling reduce on an empty array with no initial value will result in an error.

Return Value

The function accumulates the results of processing.

Examples

const arrNumbers = [1, 2, 3, 4, 5];
const reduceNumbers = (arrayNumbers, accumulatorInitVal = false) => {
    const reduceCallback = (accumulator, currentVal, currentIndex) => {
        console.log(`Current index: ${currentIndex}`);
        return accumulator + currentVal;
    };
    return accumulatorInitVal
        ? arrayNumbers.reduce(reduceCallback, accumulatorInitVal)
        : arrayNumbers.reduce(reduceCallback);
};

console.log(reduceNumbers(arrNumbers)); // 15, the initial value of the accumulator is the value of the first element of the array 1
console.log(reduceNumbers(arrNumbers, 10)); // 25, the initial value of the accumulator is 10

console.log(current index: ${currentIndex}) is to see the index value more intuitively.

The first time the initial value is not defined, the output is as follows:

Current index: 1
Current index: 2
Current index: 3
Current index: 4

The second definition of the accumulator initial value output is as follows:

Current index: 0
Current index: 1
Current index: 2
Current index: 3
Current index: 4

Next we have a weird requirement where, for some reason, we need a new array containing all of our users' full names (their last name, plus their first name), but only if they are in their 20s and their full name is 3 characters. Don’t ask us why we need such a weird data subset. The product manager asked and we are happy to help^_^

const users = [
    {
        firstName: "Jian",
        lastName: "Sun",
        age: 37,
    },
    {
        firstName: "策",
        lastName: "Sun",
        age: 21,
    },
    {
        firstName: "Ge Liang",
        lastName: "朱",
        age: 28,
    },
    {
        firstName: "備",
        lastName: "Liu",
        age: 44,
    },
    {
        firstName: "统",
        lastName: "Pang",
        age: 22,
    },
    {
        firstName: "维",
        lastName: "姜",
        age: 19,
    },
    {
        firstName: "博文",
        lastName: "Liu",
        age: 22,
    },
];
const getFullName = (user) => `${user.lastName}${user.firstName}`;
const filterByAge = (user) => user.age >= 20 && user.age < 30;

// Conventional implementation const getFilterResult = users
    // The first step is to filter users between the ages of 20 and 30.filter((user) => filterByAge(user))
    // Concatenate full names.map((user) => getFullName(user))
    // Filter.filter((fullName) => fullName.length === 3);

console.log(getFilterResult); // ['Zhuge Liang', 'Liu Bowen']

// Iteration implementation const iterationsFilterResult = (arrayResult, currentUser) => {
    const fullname = getFullName(currentUser);
    if (filterByAge(currentUser) && fullname.length === 3) {
        arrayResult.push(fullname);
    }
    return arrayResult;
};
console.log(users.reduce(iterationsFilterResult, [])); // [ 'Zhuge Liang', 'Liu Bowen' ]

Summarize

This is the end of this article about the basic use of javascript array includes and reduce. For more related javascript array includes and reduce content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Summary of using the reduce() method in JS
  • js uses the reduce method to make your code more elegant
  • JavaScript array reduce() method syntax and example analysis
  • Detailed explanation of the differences between js array find, some, filter, and reduce
  • 25 advanced uses of JS array reduce that you must know
  • JS uses the reduce() method to process tree structure data
  • Detailed explanation of reduce fold unfold usage in JS
  • Detailed explanation of JavaScript Reduce
  • Detailed explanation of JavaScript Array.reduce source code
  • 8 JS reduce usage examples and reduce operation methods

<<:  Solve the problem of PhPStudy MySQL startup failure under Windows system

>>:  Detailed explanation of VMware12 installation centOS8 configuration graphic tutorial (vm virtual machine installation centos8 tutorial)

Recommend

Detailed explanation of Windows time server configuration method

Recently, I found that the company's server t...

Web design dimensions and rules for advertising design on web pages

1. Under 800*600, if the width of the web page is...

Detailed explanation of MySQL redo log (redo log) and rollback log (undo logo)

Preface: The previous article described several c...

14 Ways to Create Website Content That Engages Your Visitors

When I surf the Net, I often see web sites filled...

HTML table markup tutorial (9): cell spacing attribute CELLSPACING

A certain distance can be set between cells in a ...

Implementation of 2D and 3D transformation in CSS3

CSS3 implements 2D plane transformation and visua...

Detailed explanation of JavaScript upload file limit parameter case

Project scenario: 1. Upload file restrictions Fun...

JavaScript implementation of verification code case

This article shares the specific code for JavaScr...

HTML page common style (recommended)

As shown below: XML/HTML CodeCopy content to clip...

What to do if the container started by docker run hangs and loses data

Scenario Description In a certain system, the fun...

MySQL uses the Partition function to implement horizontal partitioning strategy

Table of contents 1 Review 2 Five strategies for ...