2- 数组扁平化、去重与排序

406 阅读2分钟

要求:编写一个程序将数组扁平化并将扁平化后的数组去重,最终得到一个升序且不重复的一维数组。

var arr = [[1, 2, 3], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10];

1. 简洁的实现方式:Array.from(new Set(arr.flat(Infinity))).sort((a, b) => a - b)

  • arr.flat(depth):
  • flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
  • 其中,depth指定要提取嵌套数组的结构深度,默认值为1。但使用 Infinity 作为深度,展开任意深度的嵌套数组
  • 扁平化:将多维数组转化为一维数组的程序叫扁平化程序
var arr = [[1, 2, 3], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10];
/**
 * arr.flat(depth):数据扁平化;
 * new Set(arr):可以实现数组去重;
 * Array.from(arr):将类数组变成数组;
 * arr.sort((a, b) => { return a - b}):数组升序
 * arr.sort((a, b) => { return b - a}):数组倒序
 */
console.log(Array.from(new Set(arr.flat(Infinity))).sort((a, b) => a - b)); 
// 打印结果:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

2. 数据扁平化-递归的方式

function flatten(arr) {
    var _arr = arr || [],
        fArr = [],
        arrLen = _arr.length,
        item;
    for (var i = 0; i < arrLen; i++) {
        item = _arr[i];
        // 判断数据的类型
        if (_isArr(item)) {
            //数据类型为'[object Array]',递归、合并
            fArr = fArr.concat(flatten(item));
        } else {
            //基本数据类型直接添加到新数组中
            fArr.push(item);
        }
    }
    return fArr;

    function _isArr(item) {
        // {} --> new Object()
        // 判断数组的元素类型是否为数组
        return {}.toString.call(item) === '[object Array]';
    }
}
console.log(flatten(arr).sort(function (a, b) {
    return a - b;
})) //[1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 12, 13, 14]

3. 数据扁平化-在原型上封装flatten()方法--1.forEach()

Array.prototype.flatten1 = function () {
    var _arr = this,
        toStr = {}.toString,
        fArr = [];
    if (toStr.call(_arr) !== '[object Array]') {
        throw new Error('只有数组可以调用flatten方法');
    }
    _arr.forEach(function (item) {
        toStr.call(item) === '[object Array]' 
                         ? fArr = fArr.concat(item.flatten1()) 
                         : fArr.push(item);
    });
    return fArr;
}
console.log(arr.flatten1()); //[1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]

4. 数据扁平化-在原型上封装flatten()方法--2.reduce()

Array.prototype.flatten2 = function () {
    var _arr = this,
        toStr = {}.toString;
    if (toStr.call(_arr) !== '[object Array]') {
        throw new Error('只有数组可以调用flatten方法');
    }
    return _arr.reduce(function (prev, item) {
        return prev.concat(toStr.call(item) === '[object Array]' 
                                            ? item.flatten2() 
                                            : item
        );
    }, [])
}
console.log(arr.flatten2()); //[1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]

5. 数据扁平化- es6 -reduce()

//写法1:含有return
const flatten3 = (array) => {
    return array.reduce((prev, item) => {
        return prev.concat({}.toString.call(item) === '[object Array]' 
                                                  ? flatten3(item) 
                                                  : item
        );
    }, [])
}
console.log('flatten3', flatten3(arr)); 

//写法2:更简洁的写法,去掉return
const flatten4 = array =>
    array.reduce((prev, item) =>
        prev.concat({}.toString.call(item) === '[object Array]' 
                                           ? flatten4(item) 
                                           : item
         );
    , [])
console.log('flatten4', flatten4(arr));