-
Notifications
You must be signed in to change notification settings - Fork 634
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
携程&蘑菇街&bilibili:手写数组去重、扁平化函数 #30
Comments
利用while循环结合some实现数组扁平,然后利用ES6 Set去重 let arr = [[123,123,2,4,42,1,2,5], [5,8,6,54,3,9,9,3],0,7];
while(arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
let setlist = new Set([...arr]);
console.log([...setlist]); //[123, 2, 4, 42, 1, 5, 8, 6, 54, 3, 9, 0, 7] |
let arr = [[123,123,2,4,42,1,2,5], [5,8,6,54,3,9,9,3],0,7];
new Set([...arr.flat(Infinity)]) |
let arr = [[123,123,2,4,42,1,2,5], [5,8,6,54,3,9,9,3],0,7];
let str=JSON.stringify(arr);
let reg =/\[/g;
let reg2=/\]/g
str=str.replace(reg2,'').replace(reg,'')
new Set([...str.replace(reg2,'').replace(reg,'').split(",")]) |
// 扁平化 flat可以传递参数,根据要求展开depth层
const flats = arr.flat()
// 去重
[...new Set(flats)] |
题目是让自己实现数组去重和扁平化函数的, 用自带的 API 就失去意义了 |
1 数组去重函数题目中没有给出数组中元素的类型, 这里假设元素类型为 方案1: 借助哈希表数据结构记录出现过的元素
function deduplicate(arr) {
var obj = Object.create(null)
var res = []
for (var i = 0; i < arr.length; i++) {
var element = arr[i]
if (!(element in obj)) {
res.push(element)
}
}
return res
} 时间复杂度: O(n), n 为数组元素个数 注: 元素类型如果只有 方案 2: 借助有序数组去重的思路
function dedeplicate2(arr) {
arr.sort() // 这里使用自己写的快排代替即可
var i = 1
var j = 0
while(i < arr.length) {
if (arr[i] !== arr[j]) {
j += 1
arr[j] = arr[i]
}
i += 1
}
return arr.slice(0, j+1)
} 时间复杂度: O(n*logn) 2 扁平化函数适用条件: 数组或类数组对象, 对于嵌套数组可通过 /**
* @param {array}arr The array to be flatten.
* @param {number}depth The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
*/
function flat(arr, depth = 1) {
var res = []
var unflattenDepth = depth
var isArray = Object.prototype.toString.call(arr) === '[object Array]'
if (isArray) {
helper(arr)
} else { // 将类数组对象处理为数组
var slicedArr = Array.prototype.slice.call(arr)
if (slicedArr.length > 0) {
helper(slicedArr)
}
}
return res
function helper(arr) {
unflattenDepth -= 1
if (unflattenDepth < 0) {
res = res.concat(arr)
} else {
for (var i = 0; i < arr.length; i++) {
var element = arr[i]
if (Object.prototype.toString.call(element) === '[object Array]') {
helper(element)
} else {
res.push(element)
}
}
}
}
} |
数组扁平化(又称数组降维)
const test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
// 不传参数时,默认扁平化一层
test.flat()
// ["a", "b", "c", "d", ["e", ["f"]], "g"]
// 传入一个整数参数,整数即扁平化的层数
test.flat(2)
// ["a", "b", "c", "d", "e", ["f"], "g"]
// Infinity 关键字作为参数时,无论多少层嵌套,都会转为一维数组
test.flat(Infinity)
// ["a", "b", "c", "d", "e", "f", "g"]
// 传入 <=0 的整数将返回原数组,不扁平化
test.flat(0)
test.flat(-10)
// ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
// 如果原数组有空位,flat()方法会跳过空位。
["a", "b", "c", "d",,].flat()
// ["a", "b", "c", "d"]
方法一:使用 reduce 方法一次性扁平化所有: function flattenDeep(arr) {
return Array.isArray(arr)
? arr.reduce( (acc, cur) => [...acc, ...flattenDeep(cur)] , [])
: [arr]
}
// 测试
var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
flattenDeep(test)
// ["a", "b", "c", "d", "e", "f", "g"] 实现 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
}
// 测试
var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
// 不传参数时,默认扁平化一层
flat(test)
// ["a", "b", "c", "d", ["e", ["f"]], "g"]
// 传入一个整数参数,整数即扁平化的层数
flat(test, 2)
// ["a", "b", "c", "d", "e", ["f"], "g"]
// Infinity 关键字作为参数时,无论多少层嵌套,都会转为一维数组
flat(test, Infinity)
// ["a", "b", "c", "d", "e", "f", "g"]
// 传入 <=0 的整数将返回原数组,不扁平化
flat(test, 0)
flat(test, -10)
// ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]];
// 如果原数组有空位,flat()方法会跳过空位。
var arr = ["a", "b", "c", "d",,]
flat(arr)
// ["a", "b", "c", "d"] 方法二:栈一次性降维所有 function flattenDeep(arr) {
const result = []
// 将数组元素拷贝至栈,直接赋值会改变原数组
const stack = [...arr]
// 如果栈不为空,则循环遍历
while (stack.length !== 0) {
const val = stack.pop()
if (Array.isArray(val)) {
// 如果是数组再次入栈,并且展开了一层
stack.push(...val)
} else {
// 如果不是数组,就用头插法插入到结果数组中
result.unshift(val)
}
}
return result
}
// 测试
var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
flattenDeep(animals)
// ["a", "b", "c", "d", "e", "f", "g"] 数组去重方式一:Set(ES6)function unique(arr) {
return Array.from(new Set(arr))
}
// 或者
var unique = arr => [...new Set(arr)]
// 测试
var arr = [1, 2, 2, 3]
unique(arr); // [1, 2, 3] 方式二:reducefunction unique (arr) {
return arr.sort().reduce((acc, cur) => {
if (acc.length === 0 || acc[acc.length - 1] !== cur) {
acc.push(cur);
}
return acc
}, [])}
;
// 测试
var arr = [1, 2, 2, 3]
unique(arr); // [1, 2, 3] 方法三:filterfunction unique(arr) {
return arr.filter( (element, index, array) => {
return array.indexOf(element) === index
})
}
// 测试
var arr = [1, 2, 2, 3]
unique(arr); // [1, 2, 3] |
递归加Set
|
|
|
let arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN','NaN', 0, 0, 'a', 'a',{},{}]; |
No description provided.
The text was updated successfully, but these errors were encountered: