This is the fourth day of my participation in the More text Challenge. For more details, see more text Challenge

Arrays are one of the most commonly used data types in JavaScript work. Today, I will summarize array methods in various scenarios without saying much. show you the code

What is an array in JavaScript

An array is a sequence of memory locations that hold certain values. Pay attention to the emphasis, “continuous,” or contiguous, that’s important.

The underlying hardware implementation of Array is something called a memory manager, and whenever an Array is requested — the computer essentially creates a sequence of addresses in memory, each of which passes directly through the memory manager

The example in the figure above is the corresponding memory address of an array, and if you access the first element of an array or the last element of an array — that is, access any element of an array, the time complexity is constant O(1).

One of the characteristics of an array is that it is faster to access any element at random

Create an array

Array constructor

// Initialize an empty array
const arr2 = new Array(a);// Initialize an array of length 7
const arr3 = new Array(7);

// Create an array with N elements
const arr4 = new Array("red"."blue"."green");

// Fill the element with fill
const arr5 = new Array(7).fill(1);
Copy the code

Fill the element problem with fill()

const arr = new Array(7).fill({ a: 1 });
Copy the code

const arr = new Array(7).fill({ a: 1 });
console.log("---arr---beforeUpdate");
console.log(arr);

arr[4].a = 6;
console.log("---arr---");
console.log(arr);
Copy the code

Print out the previous onesarrAnd the modified ‘arr’ ‘

throughfillWhen an element is a reference type, modifying one element affects the other elements

Literal notation

// Create an empty array
const arr = [];

// Create an array with N elements
const arr1 = [1.2.3.4];
Copy the code

An array of space

When you initialize an array with an array literal, you can use a string of commas to create a hole, which the ES6 standard explicitly converts to undefined

const options = [1.5];

for (const option of options) {
  console.log(option === undefined);
}
// false
// true
// true
// true
// false
Copy the code

Array.from()

Function: converts a class array to an array instance

An array-like object is essentially any iterable structure, or structure that has a length attribute and indexable elements. The data structures with the Iterator interface are:

  • Array
  • Map
  • Set
  • String
  • TypedArray
  • Function of theargumentsobject
  • NodeListobject
// The string is split into single-character arrays
console.log(Array.from("Matt")); // ["M", "a", "t", "t"]

Const m = new Map().set(1, 2)
const m = new Map().set(1.2).set(3.4);

const s = new Set().add(1).add(2).add(3).add(4);

console.log(Array.from(m)); // [[1, 2], [3, 4]]
console.log(Array.from(s)); // [1, 2, 3, 4]
Copy the code

Array.of()

// Convert a set of parameters to an array

console.log(Array.of(1.2.3.4)); // [1, 2, 3, 4]
console.log(Array.of(undefined)); // [undefined]
Copy the code

Check whether it is an array type

  1. instanceof
  2. constructor
  3. Object.prototype.isPrototypeOf
  4. getPrototypeOf
  5. Object.prototype.toString
  6. Array.isArray
let arr = [];
// 1. instanceof
arr instanceof Array;

// 2. constructor
arr.constructor === Array;

// 3. Object.prototype.isPrototypeOf
Array.prototype.isPrototypeOf(arr);

// 4. getPrototypeOf
Object.getPrototypeOf(arr) === Array.prototype;

// 5. Object.prototype.toString
Object.prototype.toString.call(arr) === "[object Array]";

// 6.array. isArray ES6 Added - Recommended
Array.isArray(arr);
Copy the code

Finds the specified array element

  • indexOf: returns the first index in the array where a given element can be found, or -1 if it does not exist
  • lastIndexOf: Returns the index of the last element (that is, a valid JavaScript value or variable) in the array, or -1 if none exists. Look forward from the back of the array
  • includes: determines whether an array contains a specified value. Returns true if it does, false otherwise.
  • find: returns the value of the first element in the array that satisfies the provided test function. Otherwise, return undefined
  • findIndex: returns the index of the first element in the array that satisfies the provided test function. Return -1 if no corresponding element is found
  • filter: returns a new array containing all the elements that passed the tests implemented by the provided function

Here’s an example of looking for the presence of an element in an array.

const list = ["Wang"."Xiao li"."Yang"."小胡"."Gao"."Xiao zhao."."Money"."Note"];

/ / 7
const res1 = list.indexOf("Note");
/ / 7
const res2 = list.lastIndexOf("Note");
/ / note:
const res3 = list.find((item) = > item === "Note");
/ / 7
const res4 = list.findIndex((item) = > item === "Note");
// [' little Sun ']
const res5 = list.filter((item) = > item === "Note");
// true
const res6 = list.some((item) = > item === "Note");
// true
const res7 = list.includes("Note");
Copy the code

How to change the original array

Add elements

  • push: Adds one or more elements to the end of an array and returns the new length of the array

Add an object to the trailing position, using array.push.

let car = {
  color: "red".type: "cabrio".registration: new Date("2016-05-02"),
  capacity: 2}; cars.push(car);Copy the code
  • unshit: Adds one or more elements to the beginning of an array and returns the new length of the array (this method modifies the original array)

Add an object to the header, using array. unshift.

let car = {
  color: "red".type: "cabrio".registration: new Date("2016-05-02"),
  capacity: 2}; cars.unshift(car);Copy the code
  • concat: Combines two or more arrays. This method does not change the existing array, but returns a new array
const array1 = ["a"."b"."c"];
const array2 = ["d"."e"."f"];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
Copy the code

Remove elements

  • pop: Removes the last element from the array and returns its value. This method changes the length of the array
const plants = ["broccoli"."cauliflower"."cabbage"."kale"."tomato"];

console.log(plants.pop());
// expected output: "tomato"
Copy the code
  • shift: removes the first element from the array and returns its value. This method changes the length of the array.
const array1 = [1.2.3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1
Copy the code

Adds/removes elements from the middle of an array

  • splice(a,b,c): Modifies an array by removing or replacing existing elements or adding new elements in place, and returns the modified contents as an array. This method changes the array.
    • A: The starting position to cut off
    • B: The truncated length
    • C: The element to add

Add an object to the middle, using array.splice. This method is handy because it can also remove an element from an Array. Note its parameters:

Array.splice(
  {index where to start},
  {how many items to remove},
  {items to add}
);

Copy the code

Therefore, if we were to add a red convertible in the fifth position, we could use it as follows:

let car = {
  color: "red".type: "cabrio".registration: new Date("2016-05-02"),
  capacity: 2}; cars.splice(4.0, car);
Copy the code

Iterator method

What is an iterator method for an array

Applying a function to each element of an array returns a value, a set of values, and a new array

Iterator methods that do not generate a new array

  • forEach: Executes the given function once for each element of the array
const array1 = ["a"."b"."c"];

array1.forEach((element) = > console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"
Copy the code
  • every: tests whether all elements in an array pass a specified function test. It returns a Boolean value
const isBelowThreshold = (currentValue) = > currentValue < 40;

const array1 = [1.30.39.29.10.13];

console.log(array1.every(isBelowThreshold));
// expected output: true
Copy the code
  • some: tests whether at least one element in the array passes the provided function test. It returns a Boolean type
const array = [1.2.3.4.5];

// checks whether an element is even
const even = (element) = > element % 2= = =0;

console.log(array.some(even));
// expected output: true
Copy the code

An iterator method that generates a new array

  • slice(): Returns a new array object that is a shallow copy of the original array determined by begin and end (including begin, but not end). The original array will not be changed.
const animals = ["ant"."bison"."camel"."duck"."elephant"];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2.4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1.5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
Copy the code
  • reduceRight: Takes a function as an accumulator and reduces each value of the array (from right to left) to a single value.
const array1 = [
  [0.1],
  [2.3],
  [4.5],
].reduceRight((accumulator, currentValue) = > accumulator.concat(currentValue));

console.log(array1);
// expected output: Array [4, 5, 2, 3, 0, 1]
Copy the code
  • reduce: Executes a reducer function (ascending) that you provide for each element in the array and aggregates the results into a single return value.

The Reducer function accepts four parameters:

  1. Accumulator (ACC)
  2. Current Value (cur)
  3. Current Index (idx)
  4. Source Array (SRC)
const array1 = [1.2.3.4];
const reducer = (accumulator, currentValue) = > accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
Copy the code

Scenario,

  • Add up, multiply

  • Array to string

  • Map: Creates a new array with the result that each element in the array is the return value of the supplied function called once

const array1 = [1.4.9.16];

// pass a function to map
const map1 = array1.map((x) = > x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]
Copy the code
  • filter: Creates a new array containing all the elements that passed the tests implemented by the provided function
const words = [
  "spray"."limit"."elite"."exuberant"."destruction"."present",];const result = words.filter((word) = > word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Copy the code

other

  • join()Concatenates all the elements of an array (or an array-like object) into a string and returns the string. If the array has only one item, the item is returned without a delimiter.
const elements = ["Fire"."Air"."Water"];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(""));
// expected output: "FireAirWater"

console.log(elements.join("-"));
// expected output: "Fire-Air-Water"
Copy the code
  • sort(): sorts the elements of an array and returns the array. The default sort order is to convert elements to strings and then compare their UTF-16 code unit value order. This method changes the array
const months = ["March"."Jan"."Feb"."Dec"];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1.30.4.21.100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
Copy the code
  • reverse(): Reverses the positions of the elements in an array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method changes the array.
const array1 = ["one"."two"."three"];
console.log("array1:", array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log("reversed:", reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log("array1:", array1);
// expected output: "array1:" Array ["three", "two", "one"]
Copy the code

We practice

Find a specific object in an Array by its value – array.find

If you want to find a red car in the array. We can use Array.find.

let car = cars.find((car) = > car.color === "red");
Copy the code

This function returns the first element matched:

console.log(car);
// output:
/ / {
// color: 'red',
// type: 'station wagon',
// registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
// capacity: 5
// }
Copy the code

You can also search for multiple values:

let car = cars.find(car => car.color === "red" && car.type === "cabrio");

In this case, we get the last car in the list of vehicles.

Obtain multiple elements from the Array that match the condition – array.filter

The array. find method returns only one object. If you want to get all the red cars, you need to use Array.filter.

let redCars = cars.filter((car) = > car.color === "red");
console.log(redCars);
// output:
/ / /
/ / {
// color: 'red',
// type: 'station wagon',
// registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
// capacity: 5
/ /},
/ / {
// color: 'red',
// type: 'cabrio',
// registration: 'Sat Mar 03 2012 01:00:00 GMT+0100 (GMT+01:00)',
// capacity: 2
/ /}
// ]
Copy the code

Convert the Array object – array. map

Of all the Array methods, the array. map method is arguably the most frequently used: it converts an Array of objects into an Array of different objects. That’s what Array.Map does. Suppose we want to divide cars into three groups based on their size

let sizes = cars.map((car) = > {
  if (car.capacity <= 3) {
    return "small";
  }
  if (car.capacity <= 5) {
    return "medium";
  }
  return "large";
});
console.log(sizes);
// output:
// ['large','medium','medium', ..., 'small']
Copy the code

If we need more values, we can also create a new object:

let carsProperties = cars.map((car) = > {
  let properties = {
    capacity: car.capacity,
    size: "large"};if (car.capacity <= 5) {
    properties["size"] = "medium";
  }
  if (car.capacity <= 3) {
    properties["size"] = "small";
  }
  return properties;
});
console.log(carsProperties);
// output:
/ / /
// { capacity: 7, size: 'large' },
// { capacity: 5, size: 'medium' },
// { capacity: 5, size: 'medium' },
// { capacity: 2, size: 'small' },
/ /...
// ]
Copy the code

Add the property -array.foreach to each object in the Array

Array.map generates new arrays. What if we just want to make changes to the original car object? This is a good use case for the array. forEach function

cars.forEach((car) = > {
  car["size"] = "large";
  if (car.capacity <= 5) {
    car["size"] = "medium";
  }
  if (car.capacity <= 3) {
    car["size"] = "small"; }});Copy the code

Sort an Array by property – array.sort

After objects are transformed, they usually need to be sorted in one way or another.

Typically, sorting is based on the values of properties that each object has. We can use array. sort, but we need to provide a function that defines the sorting mechanism (compareFunction).

The translator’s note:

If compareFunction is specified, the array is sorted by the return value of the call to that function. That is, a and B are two elements to be compared:

  • If compareFunction(a, b) is less than 0, then a is arranged before B;
  • If compareFunction(a, b) is equal to 0, the relative positions of a and b remain the same. Note: The ECMAScript standard does not > guarantee this behavior, and not all browsers comply (e.g., Mozilla versions prior to 2003);
  • If compareFunction(a, b) is greater than 0, b will be arranged before A.
  • CompareFunction (a, b) must always return the same comparison for the same input, otherwise the sorted result will be indeterminate.

Suppose we want to sort cars in descending order.

let sortedCars = cars.sort((c1, c2) = >
  c1.capacity < c2.capacity ? 1 : c1.capacity > c2.capacity ? -1 : 0,);console.log(sortedCars);
// output:
/ / /
/ / {
// color: 'purple',
// type: 'minivan',
// registration: 'Wed Feb 01 2017 00:00:00 GMT+0100 (GMT+01:00)',
// capacity: 7
/ /},
/ / {
// color: 'red',
// type: 'station wagon',
// registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
// capacity: 5
/ /},
/ /...
// ]
Copy the code

If the result of the sort function is positive, array. sort compares two objects and places the first object in the second place. So, you can think of the sort function as a question of whether to put the first object in the second place

Always write the size comparison to zero while ensuring that the comparison values of two objects are the same to avoid unnecessary swaps.

Check whether the objects in the Array meet the conditions – array. every, array. includes

Every and array. some are used when we only need to check for specific conditions on each object.

Is there a red convertible on the car list? Do all cars carry at least four people? .

cars.some((car) = > car.color === "red" && car.type === "cabrio");
// output: true
Copy the code

You may recall that the function array.includes is similar to array.some, but only if the element is of the original type


The last

The article is shallow and humble, welcome everyone to see the comment area to leave your opinion!

Feel the harvest of students welcome to like, follow a wave!

The articles

  • The most complete ECMAScript guide
  • ECMAScript ES2015-ES6
  • ECMAScript ES2016-ES7
  • ECMAScript ES2017-ES8
  • ECMAScript ES2018-ES9
  • ECMAScript ES2019-ES10
  • ECMAScript ES2021-ES11
  • ECMAScript ES2020-ES12
  • ECMAScript ES2022-ES13