search
HomeWeb Front-endJS Tutorial[Summary] Common operation methods of JS arrays to help you improve development efficiency!

In development, there are many usage scenarios for arrays, and many array-related operations are also involved in daily life. This article summarizes some common operation methods and shares them with you. If you can use them at your fingertips during development, you can greatly improve development efficiency.

[Summary] Common operation methods of JS arrays to help you improve development efficiency!

Random sorting


1. Generate random numbers

Traverse the array, each Each cycle randomly selects a number within the array length range, and exchanges the position of this cycle with the elements at the random number position

function randomSort1(arr) {
  for (let i = 0, l = arr.length; i <p><strong>2. Generate a new array</strong></p>
  • Declare a new empty array, use a while loop, if the array length is greater than 0, continue to loop;

  • Each loop will randomize one within the array length range The number inside, push the element at the random number position into the new array,

  • and use splice (students who don’t understand splice can read here) to intercept the random number position elements, and also modifies the length of the original array;

function randomSort2(arr) {
  var mixedArr = []
  while (arr.length > 0) {
    let rc = parseInt(Math.random() * arr.length)
    mixedArr.push(arr[rc])
    arr.splice(rc, 1)
  }
  return mixedArr
}
// 例子
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(randomSort2(arr1))

3, arr.sort

  • If compareFunction If the return value of (a, b) is less than 0, then a will be arranged before b;

  • If the return value of compareFunction(a, b) is equal to 0, then a and b The relative position remains unchanged;

  • If the return value of compareFunction(a, b) is greater than 0, then b will be arranged before a;

function randomSort3(arr) {
  arr.sort(function (a, b) {
    return Math.random() - 0.5
  })
  return arr
}
// 例子
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(randomSort3(arr1))

Array object sorting


1. Sorting of a single attribute

function compare(property) {
  return function (a, b) {
    let value1 = a[property]
    let value2 = b[property]
    return value1 - value2
  }
}

let arr = [
  { name: 'zopp', age: 10 },
  { name: 'gpp', age: 18 },
  { name: 'yjj', age: 8 },
]

console.log(arr.sort(compare('age')))

2. Sorting of multiple attributes

function by(name, minor) {
  return function(o, p) {
    let a, b
    if (o && p && typeof o === 'object' && typeof p === 'object') {
      a = o[name]
      b = p[name]
      if (a === b) {
        return typeof minor === 'function' ? minor(o, p) : 0
      }
      if (typeof a === typeof b) {
        return a <h2 id="strong-Array-flattening-strong"><strong>Array flattening</strong></h2><hr><p><strong>1. Call the flat method in ES6</strong><br></p><pre class="brush:php;toolbar:false">ary = arr.flat(Infinity)

console.log([1, [2, 3, [4, 5, [6, 7]]]].flat(Infinity))

2. Ordinary recursion

let result = []
let flatten = function (arr) {
  for (let i = 0; i <p><strong>3. Iteration using reduce function</strong></p><pre class="brush:php;toolbar:false">function flatten(arr) {
  return arr.reduce((pre, cur) => {
    return pre.concat(Array.isArray(cur) ? flatten(cur) : cur)
  }, [])
}

let arr = [1, 2, [3, 4], [5, [6, 7]]]
console.log(flatten(arr))

4.Extension operator

function flatten(arr) {
  while (arr.some((item) => Array.isArray(item))) {
    arr = [].concat(...arr)
  }
  return arr
}

let arr = [1, 2, [3, 4], [5, [6, 7]]]
console.log(flatten(arr))

Array deduplication


1. Use the indexOf subscript attribute of the array to query

function unique(arr) {
  var newArr = []
  for (var i = 0; i <p><strong>2. Sort the original array first, then compare it with the adjacent ones. If they are different, store them in the new array. </strong></p><pre class="brush:php;toolbar:false">function unique(arr) {
  var formArr = arr.sort()
  var newArr = [formArr[0]]
  for (let i = 1; i <p><strong>3. Use the existing characteristics of the object's attributes. If there is no such attribute, store it in a new array. </strong></p><pre class="brush:php;toolbar:false">function unique(arr) {
  var obj = {}
  var newArr = []
  for (let i = 0; i <p><strong>4. Use the includes method on the array prototype object. </strong></p><pre class="brush:php;toolbar:false">function unique(arr) {
  var newArr = []
  for (var i = 0; i <p><strong>5. Use the filter and includes methods on the array prototype object. </strong></p><pre class="brush:php;toolbar:false">function unique(arr) {
  var newArr = []
  newArr = arr.filter(function (item) {
    return newArr.includes(item) ? '' : newArr.push(item)
  })
  return newArr
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))

6. Use the set method of ES6.

function unique(arr) {
  return Array.from(new Set(arr)) // 利用Array.from将Set结构转换成数组
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))

Deduplication based on attributes


Method 1

function unique(arr) {
  const res = new Map()
  return arr.filter((item) => !res.has(item.productName) && res.set(item.productName, 1))
}

Method 2

function unique(arr) {
  let result = {}
  let obj = {}
  for (var i = 0; i <h2 id="strong-Intersection-Union-Difference-strong"><strong>Intersection/Union/Difference</strong></h2><hr><p><strong>1. Includes method combined with filter method</strong><br> </p><pre class="brush:php;toolbar:false">let a = [1, 2, 3]
let b = [2, 4, 5]

// 并集
let union = a.concat(b.filter((v) => !a.includes(v)))
// [1,2,3,4,5]

// 交集
let intersection = a.filter((v) => b.includes(v))
// [2]

// 差集
let difference = a.concat(b).filter((v) => !a.includes(v) || !b.includes(v))
// [1,3,4,5]

2. ES6 Set data structure

let a = new Set([1, 2, 3])
let b = new Set([2, 4, 5])

// 并集
let union = new Set([...a, ...b])
// Set {1, 2, 3, 4,5}

// 交集
let intersect = new Set([...a].filter((x) => b.has(x)))
// set {2}

// a 相对于 b 的)差集
let difference = new Set([...a].filter((x) => !b.has(x)))
// Set {1, 3}

Array summation


1. Universal for loop

function sum(arr) {
  var s = 0
  for (var i = arr.length - 1; i >= 0; i--) {
    s += arr[i]
  }
  return s
}

sum([1, 2, 3, 4, 5]) // 15

2. Recursive method

function sum(arr) {
  var len = arr.length
  if (len == 0) {
    return 0
  } else if (len == 1) {
    return arr[0]
  } else {
    return arr[0] + sum(arr.slice(1))
  }
}

sum([1, 2, 3, 4, 5]) // 15

3. ES6 reduce method

function sum(arr) {
  return arr.reduce(function (prev, curr) {
    return prev + curr
  }, 0)
}

sum([1, 2, 3, 4, 5]) // 15

Array-like conversion


1. Array’s slice method

let arr = Array.prototype.slice.call(arguments)

2. ES6’s Array.from()

let arr = Array.from(arguments)

3. Extension operator...

let arr = [...arguments]

Move array up and down


function swapItems(arr, index1, index2) {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0]
  return arr
}

function up(arr, index) {
  if (index === 0) {
    return
  }
  this.swapItems(arr, index, index - 1)
}

function down(arr, index) {
  if (index === this.list.length - 1) {
    return
  }
  this.swapItems(arr, index, index + 1)
}

Convert the array into a tree structure


Convert the following data into a tree structure

let arr = [
  {
    id: 1,
    name: '1',
    pid: 0,
  },
  {
    id: 2,
    name: '1-1',
    pid: 1,
  },
  {
    id: 3,
    name: '1-1-1',
    pid: 2,
  },
  {
    id: 4,
    name: '1-2',
    pid: 1,
  },
  {
    id: 5,
    name: '1-2-2',
    pid: 4,
  },
  {
    id: 6,
    name: '1-1-1-1',
    pid: 3,
  },
  {
    id: 7,
    name: '2',
  },
]

Implementation method

function toTree(data, parentId = 0) {
  var itemArr = []
  for (var i = 0; i <p> [Related recommendations: <a href="https://www.php.cn/course/list/17.html" target="_blank">javascript learning tutorial</a><strong>]</strong></p>

The above is the detailed content of [Summary] Common operation methods of JS arrays to help you improve development efficiency!. 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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor