Home > Web Front-end > JS Tutorial > body text

What is js array flattening? Implementation of js array flattening (with code)

不言
Release: 2018-08-06 13:58:16
Original
2404 people have browsed it

This article brings you what is js array flattening? The implementation of js array flattening (with code) has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is array flattening

  1. Flattening, as the name suggests, is to reduce complexity decoration and make things It is more concise and simple, highlighting the theme.

  2. Array flattening, as you already know from the above meaning, is to transform a complex nested multi-layered array, one layer at a time, into one with fewer layers or only one layer. Array of layers.

Ps: flatten can flatten the array, and the effect will be as follows:

const arr = [1, [2, [3, 4]]];
console.log(flatten(arr)); // [1, 2, 3, 4]
Copy after login

As can be seen from this, The array processed using flatten has only one layer. Let's try to implement it.

2. Simple implementation

2.1 Ordinary recursion

  • This It is the easiest method to think of, simple and clear!

/* ES6 */
const flatten = (arr) => {
  let result = [];
  arr.forEach((item, i, arr) => {
    if (Array.isArray(item)) {
      result = result.concat(flatten(item));
    } else {
      result.push(arr[i])
    }
  })
  return result;
};

const arr = [1, [2, [3, 4]]];
console.log(flatten(arr));
Copy after login
/* ES5 */
function flatten(arr) {
  var result = [];
  for (var i = 0, len = arr.length; i < len; i++) {
    if (Array.isArray(arr[i])) {
      result = result.concat(flatten(arr[i]))
    }
    else {
      result.push(arr[i])
    }
  }
  return result;
}

const arr = [1, [2, [3, 4]]];
console.log(flatten(arr));
Copy after login

2.2 toString()

  • This method uses toString to turn the array into A comma-separated string, then iterates through the array and converts each item back to its original type.

Let’s first look at how toString turns an array into a string

[1, [2, 3, [4]]].toString()
// "1,2,3,4"
Copy after login

Complete display

/* ES6 */
const flatten = (arr) => arr.toString().split(',').map((item) => +item);

const arr = [1, [2, [3, 4]]];
console.log(flatten(arr));
Copy after login
/* ES5 */
function flatten(arr) {
  return arr.toString().split(',').map(function(item){
    return +item;
  });
}

const arr = [1, [2, [3, 4]]];
console.log(flatten(arr));
Copy after login

This However, the usage scenarios of this method are very limited. All elements in the array must be Number.
It can also be all String, you can realize the specific implementation by yourself.

2.3 [].concat.apply some

  • Use arr.some to determine if there is an array in the array , circularly call the flatten flat function (using [].concat.apply flattening), connect with concat, and finally return arr;

/* ES6 */
const flatten = (arr) => {
  while (arr.some(item => Array.isArray(item))){
    arr = [].concat.apply([], arr);
  }
  return arr;
}

const arr = [1, [2, [3, 4]]];
console.log(flatten(arr));
Copy after login
/* ES5 */
/**
* 封装Array.some
* @param {function} callback    - 回调函数
* @param {any}      currentThis - 回调函数中this指向
*/
Array.prototype.some = function (callback, currentThis){
  let context = this;
  let flag = false;
  currentThis = currentThis || this;
  for (var i = 0, len = context.length; i < len; i++) {
    const res = callback.call(currentThis, context[i], i, context);
    if (res) {
      flag = true;
    } else if (!flag) {
      flag = false;
    }
  }
  return flag;
}

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

const arr = [1, [2, [3, 4]]];
console.log(flatten(arr));
Copy after login

2.4 reduce

  • reduce itself is an iterative looper, usually used for accumulation , so according to this feature there are the following:

function flatten(arr){
  return arr.reduce(function(prev, cur){
    return prev.concat(Array.isArray(cur) ? flatten(cur) : cur)
  }, [])
}

const arr = [1, [2, [3, 4]]];
console.log(flatten(arr));
Copy after login

2.5 Destructuring operator in ES6...

  • ... Only the outermost array can be expanded each time. After being [].concat, arr will be flattened once.

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

const arr = [1, [2, [3, 4]]];
console.log(flatten(arr));
Copy after login

Recommended related articles:

Use javascript to write the lexical analysis of the four yuan arithmetic compiler

js How to implement the code of scrolling and clicking to load more data?

The above is the detailed content of What is js array flattening? Implementation of js array flattening (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!