Table of Contents
Random sorting
Array object sorting
Array flattening
Array deduplication
Deduplication based on attributes
Intersection/Union/Difference
Array summation
Array-like conversion
Move array up and down
Convert the array into a tree structure
Home Web Front-end JS Tutorial [Summary] Common operation methods of JS arrays to help you improve development efficiency!

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

Aug 04, 2022 pm 06:53 PM
javascript js array

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 < l; i++) {
    let rc = parseInt(Math.random() * l)
    // 让当前循环的数组元素和随机出来的数组元素交换位置
    const empty = arr[i]
    arr[i] = arr[rc]
    arr[rc] = empty
  }
  return arr
}

var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
// 下面两次的结果肯定是不一样的;
console.log(randomSort1(arr1))
console.log(randomSort1(arr1))
Copy after login

2. Generate a new array

  • 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))
Copy after login

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))
Copy after login

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')))
Copy after login

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 < b ? -1 : 1
      }
      return typeof a < typeof b ? -1 : 1
    } else {
      thro(&#39;error&#39;)
    }
  }
},
Copy after login

Array flattening


1. Call the flat method in ES6

ary = arr.flat(Infinity)

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

2. Ordinary recursion

let result = []
let flatten = function (arr) {
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i]
    if (Array.isArray(arr[i])) {
      flatten(item)
    } else {
      result.push(item)
    }
  }
  return result
}

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

3. Iteration using reduce function

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))
Copy after login

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))
Copy after login

Array deduplication


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

function unique(arr) {
  var newArr = []
  for (var i = 0; i < arr.length; i++) {
    if (newArr.indexOf(arr[i]) === -1) {
      newArr.push(arr[i])
    }
  }
  return newArr
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))
Copy after login

2. Sort the original array first, then compare it with the adjacent ones. If they are different, store them in the new array.

function unique(arr) {
  var formArr = arr.sort()
  var newArr = [formArr[0]]
  for (let i = 1; i < formArr.length; i++) {
    if (formArr[i] !== formArr[i - 1]) {
      newArr.push(formArr[i])
    }
  }
  return newArr
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))
Copy after login

3. Use the existing characteristics of the object's attributes. If there is no such attribute, store it in a new array.

function unique(arr) {
  var obj = {}
  var newArr = []
  for (let i = 0; i < arr.length; i++) {
    if (!obj[arr[i]]) {
      obj[arr[i]] = 1
      newArr.push(arr[i])
    }
  }
  return newArr
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))
Copy after login

4. Use the includes method on the array prototype object.

function unique(arr) {
  var newArr = []
  for (var i = 0; i < arr.length; i++) {
    if (!newArr.includes(arr[i])) {
      newArr.push(arr[i])
    }
  }
  return newArr
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))
Copy after login

5. Use the filter and includes methods on the array prototype object.

function unique(arr) {
  var newArr = []
  newArr = arr.filter(function (item) {
    return newArr.includes(item) ? &#39;&#39; : newArr.push(item)
  })
  return newArr
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))
Copy after login

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]))
Copy after login

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))
}
Copy after login

Method 2

function unique(arr) {
  let result = {}
  let obj = {}
  for (var i = 0; i < arr.length; i++) {
    if (!obj[arr[i].key]) {
      result.push(arr[i])
      obj[arr[i].key] = true
    }
  }
}
Copy after login

Intersection/Union/Difference


1. Includes method combined with filter method

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]
Copy after login

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}
Copy after login

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
Copy after login

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
Copy after login

3. ES6 reduce method

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

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

Array-like conversion


1. Array’s slice method

let arr = Array.prototype.slice.call(arguments)
Copy after login

2. ES6’s Array.from()

let arr = Array.from(arguments)
Copy after login

3. Extension operator...

let arr = [...arguments]
Copy after login

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)
}
Copy after login

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',
  },
]
Copy after login

Implementation method

function toTree(data, parentId = 0) {
  var itemArr = []
  for (var i = 0; i < data.length; i++) {
    var node = data[i]
    if (node.pid === parentId) {
      var newNode = {
        ...node,
        name: node.name,
        id: node.id,
        children: toTree(data, node.id),
      }
      itemArr.push(newNode)
    }
  }
  return itemArr
}

console.log(toTree(arr))
Copy after login

[Related recommendations: javascript learning tutorial]

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles