search
HomeWeb Front-endFront-end Q&AClassic techniques for JavaScript array operations (organized and shared)

This article brings you some related operations on arrays in JavaScript, mainly including Array object prototype methods and common operations such as deduplication, flattening, sorting, etc. I hope it will be helpful to you.

Classic techniques for JavaScript array operations (organized and shared)

JavasScript array operations, mainly including Array object prototype methods and common operations such as deduplication, flattening, sorting, etc.

Array. prototype

forEach

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

  • callback is a function executed for each element in the array. This function receives one to three parameters

  • currentValue is being processed in the array Waiting for the index of the current element

  • array optional [indicates the array being operated on]

  • thisArg optional [when executing the callback function, use As the value of this, this parameter will be ignored when using arrow functions]

forEach() executes the given function once for each element of the array

let arr = [1, 2, 3, 4, 5];
let obj = {a: 1};
arr.forEach(function(currentValue, index, array) {
  console.log("当前值:", currentValue);// 1
  console.log("当前值索引:", index);// 0
  console.log("当前处理数组:", array); // (5)[1, 2, 3, 4, 5]
  console.log("当前this指向:", this);// {a: 1}
  console.log("结束一次回调, 无需返回值");
  console.log("");
}, obj);
console.log(arr);// [1, 2, 3, 4, 5]不改变原数组

map

arr.map(callback(currentValue [, index [, array]])[, thisArg])

  • callback is a function executed by each element of the array. The function receives one to three parameters

  • currentValueThe current element being processed in the array

  • index optional [index of the current element being processed in the array]

  • array optional [array being operated on]

  • thisArg optional Select [When executing the callback function, use it as the value of this, this function will be ignored when using the arrow function]

##map() creates a new array, the result of which is the array The return value after each element in the function is called once

let arr = [1, 2, 3, 4, 5];
let obj = {a: 1};
let newArr = arr.map(function(currentValue, index, array) {
  console.log("当前值:", currentValue);// 1
  console.log("当前值索引:", index);// 0
  console.log("当前处理数组:", array); // (5)[1, 2, 3, 4, 5]
  console.log("当前this指向: ", this); // {a: 1}
  console.log("");
  return crrentValue + 10;
}, obj);
console.log(newArr);// [11, 12, 13, 14, 15]
console.log(arr);// [1, 2, 3, 4, 5]不改变原数组

push

arr.push(element1[,. .., elementN])

elementN is the element that is added to the end of the array

push() adds one or more elements to the end of the array and returns the length of the array

let arr = ['a', 'b', 'c', 'd', 'e'];
console.log(arr.push('f', 'g'));// 7
console.log(arr);// ["a", "b", "c", "d", "e", "f", "g"] 改变原数组

pop

pop() deletes the last element from the array and returns the value of the element. When the array is empty, undefind is returned. This method Change the length of the array

let arr = [1, 2, 3, 4, 5];
console.log(arr.pop());// 5
console.log(arr);// [1, 2, 3, 4] 改变原数组

shift

shift() removes the first element from the array and returns the value of the element, the The method will change the original array

let arr = [1, 2, 3, 4, 5]
console.log(arr.shift());// 1
console.log(arr);// [2, 3, 4, 5] 改变原数组

unshift##arr.unshift(element1[, ..., elementN])

unshift() adds one or more elements to the beginning of the array and returns the length of the array. This method modifies the original array

let arr = [1, 2, 3, 4, 5]
console.log(arr.unshift(-1, 0));// 7
console.log(arr);// [-1, 0, 1, 2, 3, 4, 5] 改变原数组

splicearrar.splice(start[, deleteCount[, item1[, item2[, ...]]]])

start specifies the starting position of the modification. If it exceeds the length of the array, then Add content starting from the end of the array; if it is a negative value, it indicates the number from the end of the array (counting from -1, which means -n is the nth element from the last and is equivalent to array.length-1); If the absolute value of the negative number is greater than the length of the array, it means that the starting position is position 0.

deleteCount is optional [integer], indicating the number of array elements to be removed. If deleteCount is greater than the total number of elements after start , then all elements after statr will be deleted (including the start bit). If deleteCount is omitted, or its value is greater than or equal to array.length-start (that is, if it is greater than or equal to all elements after start quantity), then all elements of the array will be deleted after start

item1, item2, ...optional [elements to be added to the array, starting from the start position. If not specified, splice() will Only delete array elements]

splice() modifies the array by deleting or replacing existing elements or adding new elements in place, and returns the modified content in the form of an array. This method will change the original array

let arr = [1, 2, 3, 4, 5]
console.log(arr.splice(1, 1));// [2]
console.log(arr);// [1, 3, 4, 5] 改变原数组

slicearr.slice([begin[, end]])

beginoptional[extraction start index] Extract the original array elements starting from this index. If this parameter is a negative number, it means starting to extract from the last few elements in the original array. If begin is omitted, the slice starts from index 0; if begin is greater than the original array length, an empty array will be returned.

end is optional [index at the end of extraction], and the extraction of the original array elements ends at this index. slice will extract all elements from the index from begin to end in the original array, including begin, but does not include end. If end is omitted, slice will be extracted to the end of the original array. If end is greater than the length of the array, slice will be extracted to the end of the array.

slice() returns a new Array object, this object is a shallow copy of the original array determined by begin and end, including begin, excluding end, the original array will not be changed

let arr = [1, 2, 3, 4, 5];
console.log(arr.sclice(1, 3));// [2, 3]
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

concat let new_array = old_array.concat(value[, value2[, ...[, valueN]]])

valueNoptional[], concatenate the array or value into New array, if the valueN parameter is omitted, concat will return a shallow copy of the existing array it is called

concat()用于合并两个或多个数组, 此方法不会更改现有数组, 而是返回一个新数组

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr3 = arr1.concat(arr2);
console.log(arr3);// [1, 2, 3, 4, 5, 6]
console.log(arr1);// [1, 2, 3] 不改变原数组

join

arr.join([separator])

separator可选 指定一个字符串来分隔数组的每个元素

join()将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串. 如果数组只有一个项目, 那么将返回该项目而不使用分隔符

let arr = ['a', 'b', 'c'];
console.log(arr.join("&"));// a&b&c
console.log(arr);// ["a", "b", "c"] 不改变数组

sort

arr.sort([compareFunction])

compareFunction可选 用来指定按某种顺序进行排列的函数. 如果省略, 元素按照转换为第字符串的各个字符的Unicode进行排序

firstEl第一个用于比较的元素

secondEl第二个用于比较的元素

sort()用原地算法对数组的元素进行排序, 并返回数组. 默认排序顺序是在将元素转换为字符串, 然后比较它们的UTF-16代码单元值序列时构建的

let arr = [1, 2, 3, 4, 5];
console.log(arr.sort((a, b) => b - a));// [5, 4, 3, 2, 1]
console.log(arr);// [5, 4, 3, 2, 1] 改变原数组

reverse

reverse()将数组中元素的位置颠倒, 并返回该数组, 该方法会改变原数组

let arr = [1, 2, 3, 4, 5];
console.log(arr.reverse());// [5, 4, 3, 2, 1]
console.log(arr);// [5, 4, 3, 2, 1] 改变原数组

every

every()测试一个数组内的所有元素是否都能通过某个指定函数的测试, 返回一个布尔值

let arr = [1, 2, 3, 4, 5];
console.log(arr.every(currentValue => currentValue > 1));// false
console.log(arr);// 不改变原数组

some

some()测试数组中是不是至少有1个元素通过了提供的测试函数, 返回一个Boolean类型的值

let arr = [1, 2, 3 ,4 ,5];
console.log(arr.some(currentValue => currentValue > 1));// true
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

filter

filter()创建一个新数组, 其包含通过所提供的测试函数的所有元素

let arr = [1, 2, 3, 4, 5];
console.log(arr.filter(currentValue => currentValue > 2));// [3, 4, 5]
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

find

find()返回数组中满足提供的测试函数的第一个元素的值, 否则返回undefined

let arr = [1, 2, 3, 4, 5];
console.log(arr.find(currentValue => currentValue > 2));// 3
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

findIndex

findIndex()返回数组中满足提供的测试函数的第一个元素的索引, 否则返回-1

let arr = [1, 2, 3, 4, 5];
console.log(arr.findIndex(currentValue => currentValue > 2));// 2
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

includes

includes()用来判断一个数组是否包含一个指定的值, 如果包含则返回true, 否则返回false

let arr = [1, 2, 3, 4, 5];
console.log(arr.includes(2));// true
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

indexOf

indexof()返回指定元素在数组中的第一个索引, 否则返回-1

let arr = [1, 2, 3, 4, 5];
console.log(arr.indexOf(2));// 1
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

lastIndexOf

lastIndexOf()返回指定元素在数组中的的最后一个索引, 如果不存在则返回-1

let arr = [1, 2, 3, 2, 1];
console.log(arr.lastIndexOf(2));// 3
console.log(arr);// [1, 2, 3, 2, 1] 不改变原数组

fill

fill()用一个固定值填充一个数组从起始索引到终止索引到全部元素, 不包括终止索引

let arr = [1, 2, 3, 4, 5];
console.log(arr.fill(0, 0, 5));// [0, 0, 0, 0, 0]
console.log(arr);// [0, 0, 0, 0 ,0] 改变数组

flat

flat()会按照一个可指定的深度递归遍历数组, 并将所有元素与遍历到的子数组中的元素合并为一个新数组返回

let arr = [1, 2, [3, 4, [5]]];
console.log(arr.flat(2));// [1, 2, 3, 4, 5]
console.log(arr);// [1, 2, [3, 4, [5]]] 不改变原数组

keys

keys()返回一个包含数组中每个索引键的Array Iterator对象

let arr = [1, 2, 3, 4, 5];
let iterator = arr.keys();
for (const key of iterator) {
  console.log(key);
  // 0
  // 1
  // 2
}
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

常用操作

数组去重

使用对象

let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3];
let obj = {};
let newArr = [];
arr.forEach(v => {
  if(!ogj[v]) {
    ogj[v] = 1;
    newArr.push(v);
  }
})
console.log(newArr);// [1, 2, 3, 5]

使用Set

let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3];
let newArr = Array.from(new Set(arr));
// let newArr = [...(new Set(arr))];// 使用ES6解构赋值
console.log(newArr);// [1, 2, 3, 5]

扁平化数组

使用flat

let arr = [1, 2, [3, 4, [5]]];
let newArr = arr.flat(2);
console.log(newArr);// [1, 2, 3, 4, 5]

递归实现flat

function _flat(arr, maxN = 1, curN = 0) {
  let newArr = [];
  if (curN >= maxN) return arr;
  arr.forEach((v, i, array) => {
    if (Array.isArray(v)) {
      newArr.push(..._flat(v, maxN, curN + 1));
    } else newArr.push(v);
  })
  return newArr;
}
let arr = [1, 2, [3, 4, [5]]];
let newArr = _flat(arr, 1);// 扁平化一层
console.log(newArr);// [1, 2, 3, 4, [5]]

统计一个字符串中出现最多的字符

使用数组将字符的ASCII码作为key制作桶

let s = "ASASRKIADAA";
let arr = [];
let base = 65;// A-Z 65-90 a-z 97-122
Array.prototype.forEach.call(s, (v) => {
  let ascii = v.charCodeAt(0) - base;
  if (arr[ascii]) {
    ++arr[ascii];
  } else arr[ascii] = 1;
})
let max = 0;
let maxIndex = 0;
arr.forEach((v, i) => {
  if (v > max) {
    max = v;
    maxIndex = i;
  }
})
console.log(String.fromCharCode(maxIndex + base), arr[maxIndex]);// A 5

找出数组中的最大值

遍历数组

let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3];
let max = -Infinity;
arr.forEach(v => {
  if (v > max) max = v;
})
console.log(max);// 5

使用Math

let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3];
let max = Math.max(...arr);
console.log(max);// 5

使用reduce

let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3];
let max = arr.reduce((a, v) => {
  return a > v ? a : v;
})
console.log(max);// 5

拷贝数组

遍历数组使用push

let arr = [1, 2, 3, 4, 5];
let newArr = [];
arr.forEach(v => newArr.push(v));
console.log(newArr);// [1, 2, 3, 4, 5]

使用concat

let arr = [1, 2, 3, 4, 5];
let newArr = [].concat(arr);
console.log(newArr);// [1, 2, 3, 4, 5]

使用slice

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

随机打乱一个数组

随机交换N次

function randomInt(a, b) {
  return Number.parseInt(Math.random() * (b-a) + a);
}
let arr = [1, 2, 3, 4, 5];
let N = arr.length;
arr.forEach((v, i, arr) => {
  let ran = randomInt(0, N);
  [arr[i], arr[ran]] = [arr[ran], arr[i]];
})
console.log(arr);

随机排序

let arr = [1, 2, 3, 4, 5];
arr.sort((v1, v2) => {
  return Math.random() >= 0.5 ? 1 : -1;
})
console.log(arr);

【相关推荐:javascript学习教程

The above is the detailed content of Classic techniques for JavaScript array operations (organized and shared). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金. If there is any infringement, please contact admin@php.cn delete
React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 19, 2025 am 12:19 AM

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

React's Purpose: Building Single-Page Applications (SPAs)React's Purpose: Building Single-Page Applications (SPAs)Apr 19, 2025 am 12:06 AM

React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

React: The Power of a JavaScript Library for Web DevelopmentReact: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React's Ecosystem: Libraries, Tools, and Best PracticesReact's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React and Frontend Development: A Comprehensive OverviewReact and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AM

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment