Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数组拍平 #4

Open
luichooy opened this issue Jul 19, 2019 · 0 comments
Open

数组拍平 #4

luichooy opened this issue Jul 19, 2019 · 0 comments

Comments

@luichooy
Copy link
Owner

luichooy commented Jul 19, 2019

已知如下数组:

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

编写一个程序将数组扁平化去并除其中重复部分数据,最终得到一个升序且不重复的数组

flat api

function flatArr(arr) {
  return [...new Set(arr.flat(Infinity))].sort((a, b) => a - b);
}

Array.prototype.join & Array.toString 方法

// join 方法
function flatArr(arr) {
  return [...new Set(arr.join().split(','))].sort((a, b) => a - b);
}

// toString 方法
function flatArr(arr) {
  return [...new Set(arr.toString().split(','))].sort((a, b) => a - b);
}

这两种方式存在的缺陷是会将数组中的每一个元素转化为字符串,即:

number -> string
null -> ''
undefined => ''
NaN -> 'NaN'
true -> 'true'
false -> 'false'
obhect -> '[object Object]'

如:

[[1, 2, 2], [3, 4, 5, 5], [6, 7, true, {name: 1}, [null, undefined,NaN, [12, 13, [14]]]], '10'].toString().split(',')


//  ["1", "2", "2", "3", "4", "5", "5", "6", "7", "true", "[object Object]", "", "", "NaN", "12", "13", "14", "10"]

函数递归拍平数组

function flatArr(arr) {
  const flat = arr => {
    let item = [];
    arr.forEach(a => {
      if (Array.isArray(a)) {
        item = item.concat(flat(a));
      } else {
        item.push(a);
      }
    });

    return item;
  };

  return [...new Set(flat(arr))].sort((a, b) => a - b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant