Introduction to JavaScript array deduplication and flattening functions

Introduction to JavaScript array deduplication and flattening functions

1. Array flattening (also known as array dimensionality reduction)

flat() method recursively traverses the array to a specified depth and merges all elements with the elements in the traversed subarray into a new array and returns it.

const test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]

// When flat does not pass parameters, it defaults to flattening one layertest.flat()
// ["a", "b", "c", "d", ["e", ["f"]], "g"]

// flat passes in an integer parameter, which is the number of flattened layers test.flat(2)
// ["a", "b", "c", "d", "e", ["f"], "g"]

// When the Infinity keyword is used as a parameter, no matter how many layers of nesting there are, it will be converted into a one-dimensional array test.flat(Infinity)
// ["a", "b", "c", "d", "e", "f", "g"]

// Passing an integer <= 0 will return the original array without flattening test.flat(0)
test.flat(-1)
// ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]

// If there are vacancies in the original array, the flat() method will skip the vacancies.
["a", "b", "c", "d",,].flat()
// ["a", "b", "c", "d"]

Method 1: Using the reduce method

Flatten all at once

function flattenDeep(arr) { 
    return Array.isArray(arr)
      ? arr.reduce( (acc, cur) => [...acc, ...flattenDeep(cur)] , [])
      : [arr]
}

// Test var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
flattenDeep(test)
// ["a", "b", "c", "d", "e", "f", "g"]

Implement the flat function:

function flat(arr, depth = 1) {
    return depth > 0
        ? arr.reduce((acc, cur) => {
        if(Array.isArray(cur)) {
            return [...acc, ...flat(cur, depth-1)]
        }
        return [...acc, cur]
    } , [])
      :arr
}

// Test var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
// When no parameters are passed, the default flattening is one layer flat(test)
// ["a", "b", "c", "d", ["e", ["f"]], "g"]

// Pass in an integer parameter, which is the number of flattened layers flat(test, 2)
// ["a", "b", "c", "d", "e", ["f"], "g"]

// When the Infinity keyword is used as a parameter, no matter how many nested levels there are, it will be converted to a one-dimensional array flat(test, Infinity)
// ["a", "b", "c", "d", "e", "f", "g"]

// Passing an integer <= 0 will return the original array without flattening flat(test, 0)
flat(test, -10)
// ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]];

// If there are vacancies in the original array, the flat() method will skip the vacancies.
var arr = ["a", "b", "c", "d",,]
flat(arr)
// ["a", "b", "c", "d"]

Method 2: Stack

Reduce all dimensions at once

function flattenDeep(arr) {
  const result = [] 
  //Copy array elements to the stack. Direct assignment will change the original array const stack = [...arr]
  // If the stack is not empty, loop through while (stack.length !== 0) {
    const val = stack.pop() 
    if (Array.isArray(val)) {
      // If the array is pushed onto the stack again and one layer is expanded stack.push(...val) 
    } else {
      // If it is not an array, insert it into the result array using head insertion result.unshift(val)
    }
  }
  return result
}

// Test var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
flattenDeep(animals)
// ["a", "b", "c", "d", "e", "f", "g"]

2. Array deduplication

Method 1: Set (ES6)

function unique(arr) {
    return Array.from(new Set(arr))
}
// or var unique = arr => [...new Set(arr)]

// Test var arr = [1, 2, 2, 3]
unique(arr); // [1, 2, 3]

Method 2: reduce

function unique(arr) {
    return arr.sort().reduce((acc, cur) => {
     if (acc.length === 0 || acc[acc.length - 1] !== cur) {
         acc.push(cur);
     }
     return acc
 }, [])}
;

// Test var arr = [1, 2, 2, 3]
unique(arr); // [1, 2, 3]


Method 3: filter

function unique(arr) { 
    return arr.filter( (element, index, array) => {
     return array.indexOf(element) === index
 })
}

// Test var arr = [1, 2, 2, 3]
unique(arr); // [1, 2, 3]

This is the end of this article about JavaScript array deduplication and flattening functions. For more relevant js array deduplication and flattening function content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Five common ways to remove duplicate arrays in JavaScript
  • JS array deduplication details
  • Detailed discussion of several methods for deduplicating JavaScript arrays
  • JavaScript array deduplication solution
  • Detailed explanation of JavaScript array deduplication
  • Seven ways to implement array deduplication in JS

<<:  Docker installation and configuration steps for Redis image

>>:  CSS HACK for IE6/IE7/IE8/IE9/FF (summary)

Recommend

CSS Paint API: A CSS-like Drawing Board

1. Use Canvas images as CSS background images The...

Detailed tutorial on installing Anaconda3 on Ubuntu 18.04

Anaconda refers to an open source Python distribu...

About React Native unable to link to the simulator

React Native can develop iOS and Android native a...

Detailed explanation of global parameter persistence in MySQL 8 new features

Table of contents Preface Global parameter persis...

JS implements the sample code of decimal conversion to hexadecimal

Preface When we write code, we occasionally encou...

Learn more about using regular expressions in JavaScript

Table of contents 1. What is a regular expression...

canvas.toDataURL image/png error handling method recommendation

Problem background: There is a requirement to tak...

MySQL 8.0.17 installation graphic tutorial

This article shares with you the MySQL 8.0.17 ins...

Neon light effects implemented with pure CSS3

This is the effect to be achieved: You can see th...

MySQL query optimization using custom variables

Table of contents Optimizing sorting queries Avoi...

MySQL 8.0.21 installation tutorial with pictures and text

1. Download the download link Click download. You...

About the problem of writing plugins for mounting DOM in vue3

Compared with vue2, vue3 has an additional concep...

JavaScript implementation of verification code case

This article shares the specific code for JavaScr...

How to set up automatic daily database backup in Linux

This article takes Centos7.6 system and Oracle11g...