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 flex and position compatibility mining notes

Today I had some free time to write a website for...

The concept and characteristics of MySQL custom variables

A MySQL custom value is a temporary container for...

How to configure nginx to limit the access frequency of the same IP

1. Add the following code to http{} in nginx.conf...

Example of creating table statements for user Scott in MySQL version of Oracle

Overview: Oracle scott user has four tables, whic...

MySQL loop inserts tens of millions of data

1. Create a test table CREATE TABLE `mysql_genara...

Analysis of the Linux input subsystem framework principle

Input subsystem framework The linux input subsyst...

How to understand Vue front-end and back-end data interaction and display

Table of contents 1. Technical Overview 2. Techni...

Getting Started Tutorial for Beginners ④: How to bind subdirectories

To understand what this means, we must first know ...

MySQL index failure principle

Table of contents 1. Reasons for index failure 2....

Understand the implementation of Nginx location matching in one article

Since the team is separating the front-end and ba...

Even a novice can understand the difference between typeof and instanceof in js

Table of contents 1. typeof 2. instanceof 3. Diff...

Docker enables multiple port mapping commands

as follows: docker run -d -p 5000:23 -p 5001:22 -...

Analysis of the pros and cons of fixed, fluid, and flexible web page layouts

There is a question that has troubled web designe...

Various ways to modify the background image color using CSS3

CSS3 can change the color of pictures. From now o...