JS base array type

Posted by KFC on Thu, 27 Jan 2022 06:32:52 +0100

Declaration array

Array is a collection of multiple variable values. Array is an instance of array object, so you can call methods like objects.

Create array

Creating arrays using object mode

console.log(new Array(1, 'wgchen', 'willem')); // [1, 'wgchen', 'willem']

Using literal creation is a simple recommended practice

const array = ["wgchen", "willem"];

Multidimensional array definition

const array = [["wgchen"], ["willem"]];
console.log(array[1][0]); // willem

Array is a reference type. You can use const to declare and modify its value

const array = ["wgchen", "willem"];
array.push("ycc");
console.log(array); // ['wgchen', 'willem', 'ycc']

Use the length attribute of the prototype to get the number of array elements

let hd = ["wgchen", "willem"];
console.log(hd.length); //2

Array can set any value. Here is how to add an array using index

let hd = ["wgchen"];
hd[1] = "willem";

console.log(hd) // ['wgchen', 'willem']

Next, set array No. 3 directly, and the array with 1 / 2 index will be defined as null value

let hd = ["wgchen"];
hd[3] = "willem";
console.log(hd.length); //4
console.log(hd); // ['wgchen ', empty × 2, 'willem']

Declare an array of multiple empty elements

let hd = new Array(3);

console.log(hd.length);
console.log(hd);

Array.of

Use array The difference between of and new Array is that when a parameter is set, an empty element array will not be created

let hd = Array.of(3);
console.log(hd); //[3]

hd = Array.of(1, 2, 3);
console.log(hd); //[1, 2, 3]

Type detection

Detect whether the variable is of array type

console.log(Array.isArray([1, "wgchen", "willem"])); //true
console.log(Array.isArray(9)); //false

Type conversion

You can convert arrays to strings or other types to arrays.

String to array

Most data types can be used The toString() function converts to a string.

console.log(([1, 2, 3]).toString()); // 1,2,3

You can also use the function String to convert to a String.

console.log(String([1, 2, 3]));

Or join as a string

console.log([1, 2, 3].join("-"));//1-2-3

Array.from converts an array of classes to an array

Use array From can convert a class array into an array. A class array refers to an object that contains the length attribute or can be iterated.

The first parameter is the data to be converted
The second parameter is a callback method similar to the map function

let str = 'wgcehn';
console.log(Array.from(str)); // ['w', 'g', 'c', 'e', 'h', 'n']

After setting the length property for an object, it can also be converted to an array, but the subscript is a numeric value or a numeric string

let user = {
  0: 'wgchen',
  '1': 18,
  length: 2
};
console.log(Array.from(user)); // ["wgchen", 18]

DOM elements are converted into arrays, and then array functions are used,
The second parameter is similar to the method of the map function, which performs functional processing on array elements.

<body>
    <button message="wgchen">button</button>
    <button message="willem">button</button>
</body>

<script>
    let btns = document.querySelectorAll('button');
    console.log(btns); //Contains the length attribute
    
    Array.from(btns, (item) => {
        item.style.background = 'red';
    });
</script>

Expand syntax

Convert NodeList to array operation using expansion syntax

<style>
    .hide {
      display: none;
    }
</style>

<body>
  <div>wgchen</div>
  <div>willem</div>
</body>

<script>
  let divs = document.querySelectorAll("div");
  
  [...divs].map(function(div) {
    div.addEventListener("click", function() {
      this.classList.toggle("hide");
    });
  });
</script>

Array merge

Using the expansion syntax to merge arrays is simpler than concat. Use You can expand an array into multiple values.

let a = [1, 2, 3];
let b = ['a', 'wgchen', ...a];
console.log(b); // ['a', 'wgchen', 1, 2, 3]

Function parameters

The presentation syntax can be used instead of arguments to receive any number of parameters

function hd(...args) {
  console.log(args);
}

hd(1, 2, 3, "wgchen"); // [1, 2, 3, 'wgchen']

It can also be used to receive some parameters

function hd(site, ...args) {
  console.log(site, args); // 
}

hd("wgchen", 1, 2, 3);

Node conversion

DOM nodes can be converted into arrays. The following example cannot use filter because it is a node list

<body>
    <button message="wgchen">button</button>
    <button message="willem">button</button>
</body>

<script>
    let btns = document.querySelectorAll('button');
    btns.map((item) => {
        console.log(item); //TypeError: btns.filter is not a function
    })
</script>

After using the expansion syntax, you can use the data method

<style>
    .hide {
      display: none;
    }
</style>

<body>
    <div><button message="wgchen">button</button></div>
    <div><button message="willem">button</button></div>
</body>

<script>
    let divs = document.querySelectorAll("div");
    [...divs].map(function (div) {
        div.addEventListener("click", function () {
            this.classList.toggle("hide");
        });
    });
</script>

Prototype processing can also be used after learning the following chapters

<body>
    <button message="wgchen">button</button>
    <button message="willem">button</button>
</body>

<script>
    let btns = document.querySelectorAll('button');
    Array.prototype.map.call(btns, (item) => {
        item.style.background = 'red';
    });
</script>

Destructuring assignment

Deconstruction is a more concise assignment feature, which can be understood as decomposing the structure of a data

Use var/let/const declaration for construction

Basic use

Here is the basic usage syntax

//Array usage
let [name, url] = ['wgchen', 'ycc'];
console.log(name);   // wgchen 

Deconstruct assignment array

function hd() {
    return ['wgchen', 'willem'];
}

let [a, b] = hd();
console.log(a); // wgchen

Residual deconstruction refers to using a variable to receive residual parameters

let [a, ...b] = ['wgchen', 'ycc', 'willem'];
console.log(b); // ['ycc', 'willem']

If the variable has been initialized, use () to define the assignment expression. The strict mode will report an error, so it is not recommended.

let web = "wgchen";
[web, url] = ["wgchen", "ycc"];

console.log(web); // wgchen

String deconstruction

"use strict";
const [...a] = "wgchen";

console.log(a); // ['w', 'g', 'c', 'h', 'e', 'n']

Strict mode

Declaration instructions may not be used in non strict mode, but must be used in strict mode.
Therefore, it is recommended to use declarations such as let.

"use strict";

[web, url] = ["wgchen", "ycc"];
console.log(web); // Uncaught ReferenceError: web is not defined

Concise definition

Assign only some variables

let [,url]=['ycc','wgchen'];
console.log(url); // wgchen

Get multiple values using expansion syntax

let [name, ...arr] = ['wgchen', 'willem', 'ycc'];
console.log(name, arr); // wgchen ['willem', 'ycc']

Default value

Set default values for variables

let [name, site = 'wgchen'] = ['willem'];

console.log(site); // wgchen
console.log(name); // willem

Function parameters

Use of array parameters

function hd([a, b]) {
	console.log(a, b); // wgchen ycc
}

hd(['wgchen', 'ycc']);

Manage array elements

Basic use

Use the index starting from 0 to change the array

let arr = [1, "wgchen", "willem"];
arr[1] = 'wgchen.blog';

console.log(arr); // [1, 'wgchen.blog', 'willem']

Retrieve elements from array

let arr = [1, "wgchen", "willem"];
arr[arr.length] = 'wgchen.blog';

console.log(arr); // [1, 'wgchen', 'willem', 'wgchen.blog']

Extended syntax

Batch add elements using presentation syntax

let arr = ["wgchen", "willem"];
let hd = ["wgchen.blog"];
hd.push(...arr);

console.log(hd); // ['wgchen.blog', 'wgchen', 'willem']

Push push element

Press in the element, directly change the meta array, and the return value is the number of array elements

let arr = ["wgchen", "willem"];
console.log(arr.push('ycc', 'haoren')); // 4
console.log(arr); // ['wgchen', 'willem', 'ycc', 'haoren']

Create a new array based on the interval

function rangeArray(begin, end) {
    const array = [];
    for (let i = begin; i <= end; i++) {
        array.push(i);
    }
    return array;
}

console.log(rangeArray(1, 6)); // [1, 2, 3, 4, 5, 6]

Pop pop element from end

Pop up the element from the end, directly change the meta array, and the return value is the pop-up element

let arr = ["wgchen", "willem"];
console.log(arr.pop()); // willem
console.log(arr); // ['wgchen']

shift takes an element from the front of the array

Take an element from the front of the array

let arr = ["wgchen", "willem"];
console.log(arr.shift()); // wgchen
console.log(arr); // ['willem']

unshift adds an element from the front of the array

Add elements from the front of the array

let arr = ["wgchen", "willem"];

console.log(arr.unshift('ycc', 'wg')); //4
console.log(arr); // ['ycc', 'wg', 'wgchen', 'willem']

Fill fill array elements

Fill array elements with fill

// Array(4) 0: "wgchen" 1: "wgchen" 2: "wgchen" 3: "wgchen" length: 4
console.dir(Array(4).fill("wgchen")); 

Specify fill location

console.log([1, 2, 3, 4].fill("wgchen", 1, 2)); // [1, 'wgchen', 3, 4]

slice intercepts some elements from the array and combines them into a new array

Use slice method to intercept some elements from the array and combine them into a new array (without changing the original array). When the second parameter is not passed, intercept the last element of the array.

let arr = [0, 1, 2, 3, 4, 5, 6];
console.log(arr.slice(1, 3)); // [1,2]

Not setting parameters is to get all elements

let arr = [0, 1, 2, 3, 4, 5, 6];
console.log(arr.slice()); //[0, 1, 2, 3, 4, 5, 6]

splice adds, deletes, and replaces elements in an array

Use the splice method to add, delete and replace the elements in the array. The original array will be changed, and the return value is the deleted element.

When deleting array elements, the first parameter is where to start deletion, and the second parameter is the number of deleted elements.

let arr = [0, 1, 2, 3, 4, 5, 6];

console.log(arr.splice(1, 3)); //Return deleted element [1, 2, 3] 
console.log(arr); //Original array after deleting data [0, 4, 5, 6]

Delete the last element by modifying the length

let arr = ["wgchen", "willem"];

arr.length = arr.length - 1;
console.log(arr);  // ['wgchen']

Set the element added at the deletion location by specifying the third parameter

let arr = [0, 1, 2, 3, 4, 5, 6];
console.log(arr.splice(1, 3, 'willem', 'ycc')); // [1, 2, 3]
console.log(arr); // [0, 'willem', 'ycc', 4, 5, 6]

Add element to end

let arr = [0, 1, 2, 3, 4, 5, 6];
console.log(arr.splice(arr.length, 0, 'willem', 'ycc')); // []
console.log(arr); // [0, 1, 2, 3, 4, 5, 6, 'willem', 'ycc']

Add element before array

let arr = [0, 1, 2, 3, 4, 5, 6];
console.log(arr.splice(0, 0, 'wgchen', 'willem')); // []
console.log(arr); // ['wgchen', 'willem', 0, 1, 2, 3, 4, 5, 6]

Array element position adjustment function

function move(array, before, to) {
  if (before < 0 || to >= array.length) {
    console.error("Wrong location specified");
    return;
  }
  const newArray = [...array];
  const elem = newArray.splice(before, 1);
  newArray.splice(to, 0, ...elem);
  return newArray;
}
const array = [1, 2, 3, 4];
console.table(move(array, 0, 3));

Empty array

Changing the array value to [] can empty the array. If there are multiple references, the array exists in memory and is referenced by other variables.

let user = [{ name: "wgchen" }, { name: "willem" }];
let cms = user;
user = [];

console.log(user); // []
console.log(cms); // [{...}, {...}]

You can also empty the array by setting the length of the array to 0

let user = [{ name: "wgchen" }, { name: "willem" }];
user.length = 0;
console.log(user); // []

Use the splice method to delete all array elements

let user = [{ name: "wgchen" }, { name: "willem" }];
user.splice(0, user.length);
console.log(user); // []

Use pop/shift to delete all elements to empty the array

let user = [{ name: "wgchen" }, { name: "willem" }];
while (user.pop()) {}
console.log(user); // []

Merge split

join arrays are concatenated into strings

let arr = [1, "wgchen", "willem"];
console.log(arr.join('-')); // 1-wgchen-willem

split splits a string into arrays

The split method is used to divide a string into arrays, similar to the inverse function of the join method.

let price = "99,78,68";
console.log(price.split(",")); //["99", "78", "68"]

concat connects two or more arrays

concat method is used to connect two or more arrays. If the element is a value type, it is a copy operation. If it is a reference type, it still points to the same object.

let array = ["wgchen", "willem"];
let hd = [1, 2];
let cms = [3, 4];
console.log(array.concat(hd, cms)); // ['wgchen', 'willem', 1, 2, 3, 4]

You can also use extended syntax to implement connections

console.log([...array, ...hd, ...cms]);

copyWithin copies part of an array to another location in the same array

Use copyWithin to copy a part from the array to another location in the same array.

Syntax description

array.copyWithin(target, start, end)

Parameter description

parameterdescribe
targetRequired. Copy to the specified target index location.
startOptional. The starting position of the element copy.
endOptional. The index location where replication stops (array. Length by default). If it is negative, it means the reciprocal.

Array lookup element

The array contains a variety of search functions. You need to master these functions clearly, and then select the appropriate functions according to different scenarios.

indexOf finds the location of the element from front to back

Use indexOf to find the position where the element appears from front to back. If it is not found, return - 1.

let arr = [7, 3, 2, 8, 2, 6];
console.log(arr.indexOf(2)); // 2 find where 2 appears from the front

As shown in the following code, using indexOf to find the string will not be found, because indexOf is similar to = = = and is a strict type constraint.

let arr = [7, 3, 2, '8', 2, 6];
console.log(arr.indexOf(8)); // -1

The second parameter is used to specify where to start the search

let arr = [7, 3, 2, 8, 2, 6];

//Find backwards from the second element
console.log(arr.indexOf(2, 3)); // 4

lastIndexOf finds the position where the element appears from back to front

Use lastIndexOf to find the position where the element appears from back to front. If it is not found, return - 1.

let arr = [7, 3, 2, 8, 2, 6];
console.log(arr.lastIndexOf(2)); // 4 find where 2 appears from the back

The second parameter is used to specify where to start the search

let arr = [7, 3, 2, 8, 2, 6];
//Look forward from the fifth element
console.log(arr.lastIndexOf(2, 5));

//Look forward from the last character
console.log(arr.lastIndexOf(2, -2));

includes the return value of the lookup string is a boolean type

Use includes to find the string. The return value is Boolean, which is more convenient to judge

let arr = [7, 3, 2, 6];
console.log(arr.includes(6)); //true

Let's implement a self-contained include function to deepen our understanding of the include method

function includes(array, item) {
  for (const value of array)
    if (item === value) return true;
  return false;
}

console.log(includes([1, 2, 3, 4], 3)); //true

The find method will return the value after finding it

If not found, the return value is undefined
Return the value found for the first time. Do not continue to search

let arr = ["wgchen", "willem", "ycc"];

let find = arr.find(function(item) {
  return item == "willem";
});

console.log(find); // willem

Reference types cannot be found using includes, etc., because their memory addresses are not equal

const user = [{ name: "Li Si" }, { name: "Zhang San" }, { name: "Wang Wu" }];
const find = user.includes({ name: "Zhang San" });
console.log(find); // false

Find can easily find reference types

const user = [{ name: "Li Si" }, { name: "Zhang San" }, { name: "Wang Wu" }];
const find = user.find(user => (user.name = "Zhang San"));
console.log(find); // {name: 'Zhang San'}

findIndex returns the index value

The difference between findIndex and find is that it returns the index value. The parameters are also: current value, index and operation array.

- 1 will be returned if the search fails

let arr = [7, 3, 2, '8', 2, 6];

console.log(arr.findIndex(function (v) {
	return v == 8;
})); //3

find principle

Here is a custom function

let arr = [1, 2, 3, 4, 5];

function find(array, callback) {
  for (const value of array) {
    if (callback(value) === true) return value;
  }
  return undefined;
}

let res = find(arr, function(item) {
  return item == 23;
});

console.log(res); // undefined

explain
The item in function(item) is the value in callback(value).

let arr = [1, 2, 3, 4, 5];
function find(array, callback) {
  for (const value of array) {
    if (callback(value) === true) return value;
  }
  return undefined;
}
let res = find(arr, function(item) {
    console.log(item);
  return item == 5;
});
console.log(res);


Next, add a prototype method implementation

let arr = [1, 2, 3, 4, 5];

Array.prototype.findValue = function(callback) {
  for (const value of this) {
    if (callback(value) === true) return value;
  }
  return undefined;
};

let re = arr.findValue(function(item) {
  return item == 2;
});
console.log(re); // 2

Array sorting

reverse reverses the order of the array

let arr = [1, 4, 2, 9];
console.log(arr.reverse()); //[9, 2, 4, 1]

sort compares two values at a time

Sort uses two values at a time to compare array sort((a,b)=>a-b

  • Returns the negative number a, from small to large, ahead of b
  • Returns a positive number b, ahead of A
  • Do not move when returning to 0

By default, array elements are sorted from less than large

let arr = [1, 4, 2, 9];
console.log(arr.sort()); //[1, 2, 4, 9]

Use the sorting function to sort from large to small. Compare parameter 1 with parameter 2 and return positive numbers in descending order and negative numbers in ascending order

let arr = [1, 4, 2, 9];

console.log(arr.sort(function (v1, v2) {
	return v2 - v1;
})); // [9, 4, 2, 1]

The following is the ranking of course hits from high to low

let lessons = [
  { title: "Media query responsive layout", click: 78 },
  { title: "FLEX Elastic box model", click: 12 },
  { title: "MYSQL Random operation of multi table query", click: 99 }
];

let sortLessons = lessons.sort((v1, v2) => v2.click - v1.click);
console.log(sortLessons);

Sorting principle

let arr = [1, 5, 3, 9, 7];

function sort(array, callback) {
  for (const n in array) {
    for (const m in array) {
      if (callback(array[n], array[m]) < 0) {
        let temp = array[n];
        array[n] = array[m];
        array[m] = temp;
      }
    }
  }
  return array;
}

arr = sort(arr, function(a, b) {
  return a - b;
});

console.table(arr);

Loop traversal

for loops through the array based on its length

let lessons = [
	{title: 'Media query responsive layout',category: 'css'},
    {title: 'FLEX Elastic box model',category: 'css'},
	{title: 'MYSQL Random operation of multi table query',category: 'mysql'}
];

for (let i = 0; i < lessons.length; i++) {
  lessons[i] = `wgchen: ${lessons[i].title}`;
}

console.log(lessons);

forEach causes the function to act on each array element, but does not return a value.

The following example is to intercept the five characters of the label.

let lessons = [
	{title: 'Media query responsive layout',category: 'css'},
    {title: 'FLEX Elastic box model',category: 'css'},
	{title: 'MYSQL Random operation of multi table query',category: 'mysql'}
];

lessons.forEach((item, index, array) => {
    item.title = item.title.substr(0, 5);
});
console.log(lessons);

The key value during for/in traversal is the index of the array

let lessons = [
	{title: 'Media query responsive layout',category: 'css'},
    {title: 'FLEX Elastic box model',category: 'css'},
	{title: 'MYSQL Random operation of multi table query',category: 'mysql'}
];

for (const key in lessons) {
    console.log(`title: ${lessons[key].title}`);
}

for/of takes the value instead of the index in each loop

let lessons = [
	{title: 'Media query responsive layout',category: 'css'},
    {title: 'FLEX Elastic box model',category: 'css'},
	{title: 'MYSQL Random operation of multi table query',category: 'mysql'}
];

for (const item of lessons) {
  console.log(`
    title: ${item.title}
    column: ${item.category == "css" ? "front end" : "database"}
  `);
}


Use the iterative object traversal of the array to obtain the index and value (the knowledge of iterators will be discussed in later chapters)

const hd = ['wgchen', 'wgchen'];
const iterator = hd.entries();

console.log(iterator.next()); // value:{0:0,1:'wgchen'}
console.log(iterator.next()); // value:{0:1,1:'willem'}


In this way, you can use the deconstruction feature and for/of to traverse and obtain the index and value

const hd = ["willem", "wgcehn"];

for (const [key, value] of hd.entries()) {
  console.log(key, value); //So you can traverse
}

Take the maximum value in the array

function arrayMax(array) {
  let max = array[0];
  for (const elem of array) {
    max = max > elem ? max : elem;
  }
  return max;
}

console.log(arrayMax([1, 3, 2, 9]));

Iterator method

A variety of iterator methods can be used in arrays, which will be explained in later chapters.

keys gets the index by iterating over the object

const hd = ['wgchen', 'willem'];
const keys = hd.keys();
console.log(keys.next());
console.log(keys.next());

Get all keys of the array

"use strict";
const arr = ["a", "b", "c", "wgchen"];

for (const key of arr.keys()) {
  console.log(key);
}


Use while traversal

let arr = ["wgchen", "willem", "ycc"];
let i = 0;
while (arr[i]) {
    console.log(arr[i]);
    i++;
}

values gets the value by iterating over the object

let arr = ["wgchen", "willem", "ycc"];
const values = arr.values();

console.log(values.next()); // {value: 'wgchen', done: false}
console.log(values.next()); // {value: 'willem', done: false}
console.log(values.next()); // {value: 'ycc', done: false}

Gets all the values of the array

"use strict";
const arr = ["a", "b", "c", "wgchen"];

for (const value of arr.values()) {
  console.log(value);
}

entries returns all key value pairs of the array

Next, use the deconstruction syntax loop

"use strict";
const arr = ["a", "b", "c", "wgchen"];

for (const [key, value] of arr.entries()) {
  console.log(key, value);
}


Deconstruction and acquisition content (the object chapter will explain in detail)

const hd = ["wgchen", "willem"];
const iterator = hd.entries();

let {done,value: [k, v]} = iterator.next();

console.log(v); // wgchen

Extension method

every is used for recursive detection elements

All element operations must return true before the result is true.

Check whether all the students in the class have passed the JS

const user = [
  { name: "Li Si", js: 89 },
  { name: "Ma Liu", js: 55 },
  { name: "Zhang San", js: 78 }
];
const resust = user.every(user => user.js >= 60);
console.log(resust); // false

Keyword check of title

let words = ['wgchen', 'Beijing'];
let title = 'wgchen Continue to share technical tutorials in Beijing';

let state = words.every(function (item, index, array) {
  return title.indexOf(item) >= 0;
});

console.log(state); // true

// The title must contain all keywords
if (state == false) console.log('The title must contain all keywords'); 

some recursive detection element

Use some function to recursively detect elements. If one of them returns true, the result of the expression is true. The first parameter is the element, the second parameter is the index, and the third parameter is the original array.

The following is an example of using some to detect rule keywords. If a word is matched, it will prompt violations.

let words = ['wgchen', 'Beijing', 'Wuhan'];
let title = 'wgchen Continuously share technical tutorials'

let state = words.some(function (item, index, array) {
	return title.indexOf(item) >= 0;
});

if (state) console.log('The title contains illegal keywords'); // The title contains illegal keywords

Filter filter elements in data

Use filter to filter the elements in the data. The following is the course to get all the elements in the CSS column.

let lessons = [
  {title: 'Media query responsive layout',category: 'css'},
  {title: 'FLEX Elastic box model',category: 'css'},
  {title: 'MYSQL Random operation of multi table query',category: 'mysql'}
];

let cssLessons = lessons.filter(function (item, index, array) {
  if (item.category.toLowerCase() == 'css') {
    return true;
  }
});

console.log(cssLessons);


Let's write a method of filtering elements to deepen some techniques

function except(array, excepts) {
  const newArray = [];
  
  for (const elem of array)
    if (!excepts.includes(elem)) newArray.push(elem);
    
  return newArray;
}

const array = [1, 2, 3, 4];
console.log(except(array, [2, 3])); // [1,4]

Map map applies functions on all elements of the array

Using map mapping, you can apply functions on all elements of the array to map out new values.

Gets a new array of all header combinations of the array

let lessons = [
  {title: 'Media query responsive layout',category: 'css'},
  {title: 'FLEX Elastic box model',category: 'css'},
  {title: 'MYSQL Random operation of multi table query',category: 'mysql'}
];

console.log(lessons.map(item => item.title));

Add wgchen to all titles

let lessons = [
  {title: 'Media query responsive layout',category: 'css'},
  {title: 'FLEX Elastic box model',category: 'css'},
  {title: 'MYSQL Random operation of multi table query',category: 'mysql'}
];

lessons = lessons.map(function (item, index, array) {
    item.title = `[wgchen] ${item['title']}`;
    return item;
});

console.log(lessons);

reduce iterates over all elements of the array

Use the reduce and reduceRight functions to iterate over all elements of the array. Reduce starts from the front and reduceRight starts from the back. The sum of the number of clicks in the course is calculated by function below.

The first parameter is the execution function
The second parameter is the initial value

  • Loop through all elements when passing in the second parameter
  • When the second parameter is not passed, the loop starts from the second element

The function parameters are described below

parameterexplain
prevThe result returned from the last call to the callback function
curCurrent element value
indexCurrent index
arrayOriginal array

Using reduce to realize array de duplication

let arr = [1, 2, 6, 2, 1];

let filterArr = arr.reduce((pre, cur, index, array) => {
  if (pre.includes(cur) === false) {
      pre = [...pre, cur];
  }
  return pre;
}, [])

console.log(filterArr); // [1,2,6]

Examples

<p id="demo">Output: 100</p>

const numbers = [175, 50, 25];
document.getElementById("demo").innerHTML = numbers.reduce(myFunc);

function myFunc(total, num) {
  return total - num;
}

Definition and Usage

The reduce() method reduces the array to a single value.
The reduce() method executes the provided function for each value of the array (from left to right).

The return value of the function is stored in the accumulator (result / total).
Note: for array elements without values, the reduce() method is not executed.
Note: the reduce() method does not change the original array.

const numbers = [175, 50, 25];
numbers.reduce(myFunc);

function myFunc(total, num) {
  console.log(total,num);
}

const numbers = [175, 50, 25,30];
numbers.reduce(myFunc);

function myFunc(total, num) {
  console.log(total,num);
}

Counts the number of occurrences of the element

function countArrayELem(array, elem) {
  return array.reduce((total, cur) => (total += cur == elem ? 1 : 0), 0);
}

let numbers = [1, 2, 3, 1, 5];
console.log(countArrayELem(numbers, 1)); //2

Take the maximum value in the array

function arrayMax(array) {
  return array.reduce(
  	(max, elem) => (max > elem ? max : elem), array[0]
  );
}

console.log(arrayMax([1, 3, 2, 9]));

Take the goods with the highest price

let cart = [
  { name: "iphone", price: 12000 },
  { name: "imac", price: 25000 },
  { name: "ipad", price: 3600 }
];

function maxPrice(array) {
  return array.reduce(
    (goods, elem) => (goods.price > elem.price ? goods : elem),
    array[0]
  );
}
console.log(maxPrice(cart));

Calculate the total price of goods in the shopping cart

let cart = [
  { name: "iphone", price: 12000 },
  { name: "imac", price: 25000 },
  { name: "ipad", price: 3600 }
];

const total = cart.reduce(
	(total, goods) => total += goods.price, 0
);
console.log(total); //40600

Get the product name with the price of more than 10000

let goods = [
  { name: "iphone", price: 12000 },
  { name: "imac", price: 25000 },
  { name: "ipad", price: 3600 }
];

function getNameByPrice(array, price) {
  return array.reduce((goods, elem) => {
    if (elem.price > price) {
      goods.push(elem);
    }
    return goods;
  }, []).map(elem => elem.name);
}

console.table(getNameByPrice(goods, 10000));

Animation case

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>wgchen</title>
</head>

<style>
    body {
      width: 100vw;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #2c3e50;
    }
  
    * {
      padding: 0;
      margin: 0;
    }
    div {
      color: #9b59b6;
      font-size: 5em;
      font-weight: bold;
      text-transform: uppercase;
      cursor: pointer;
    }
    div > span {
      position: relative;
      display: inline-block;
    }
    .changeColor {
      animation-name: changeColor;
      animation-duration: 1s;
      animation-direction: alternate;
      animation-iteration-count: 2;
      animation-timing-function: linear;
    }
    @keyframes changeColor {
      50% {
        color: #f1c40f;
        transform: scale(1.5);
      }
      to {
        color: #9b59b6;
        transform: scale(0.5);
      }
    }
  </style>
  
  <body>
    <div>wgchen.blog.csdn.net</div>
  </body>
  
  <script>
    let div = document.querySelector("div");
    /*
        console.log([...div.textContent]); 
        ['w', 'g', 'c', 'h', 'e', 'n', '.', 'b', 'l', 'o', 'g', '.', 'c', 's', 'd', 'n', '.', 'n', 'e', 't']
    */

    [...div.textContent].reduce((pre, cur, index) => {
        // console.log(pre); // 0
      pre == index && (div.innerHTML = "");

      let span = document.createElement("span");
      span.textContent = cur;
      div.appendChild(span);

      span.addEventListener("mouseover", function() {
        this.classList.add("changeColor");
      });

      span.addEventListener("animationend", function() {
        this.classList.remove("changeColor");
      });

    }, 0);
  </script>

</html>

Topics: Javascript Front-end