Array deduplication
The test data for array deduplication is as follows:
const sourceArray = [
null, 6, 34, '6', [], 'a', undefined, 'f', 'a', [],
34, null, {}, true, NaN, {}, NaN, false, true, undefined
]
const filterArray = unique(sourceArray)
Double loop
function unique(sourceData) {
let flag
let filterArray = []
for (let i = 0; i < sourceData.length; i++) {
flag = true
for (let j = 0; j < filterArray.length; j++) {
if (sourceData[i] === filterArray[j]) {
flag = false
break
}
}
if (flag) {
filterArray.push(sourceData[i])
}
}
return filterArray
}
// [null, 6, 34, "6", [], "a", undefined, "f", [], {}, true, NaN, {}, NaN, false]
function unique(sourceData) {
let flag
let filterArray = []
for (let i = 0; i < sourceData.length; i++) {
flag = true
for (let j = i + 1; j < sourceData.length; j++) {
if (sourceData[i] === sourceData[j]) {
flag = false
break
}
}
if (flag) {
filterArray.push(sourceData[i])
}
}
return filterArray
}
// [6, "6", [], "f", "a", [], 34, null, {}, NaN, {}, NaN, false, true, undefined]
indexOf
function unique(sourceData) {
return sourceData.filter((item, index) => {
return sourceData.indexOf(item) === index
})
}
// [null, 6, 34, "6", [], "a", undefined, "f", [], {}, true, {}, false]
Note: The returned sourceData.indexOf(NaN) is always -1, and the index can never be -1, so NaN is filtered out
function unique(sourceData) {
let filterArray = []
sourceData.forEach(item => {
// filterArray数组中没有item
if (filterArray.indexOf(item) === -1) {
filterArray.push(item)
}
})
return filterArray
}
// [null, 6, 34, "6", [], "a", undefined, "f", [], {}, true, NaN, {}, NaN, false]
sort
function unique(sourceData) {
let filterArray = []
sourceData.sort()
for (let i = 0; i < sourceData.length; i++) {
if (sourceData[i] !== filterArray[filterArray.length - 1]) {
filterArray.push(sourceData[i])
}
}
return filterArray
}
// [[], [], 34, 6, "6", NaN, NaN, {}, {}, "a", "f", false, null, true, undefined]
Note: The above schemes are not applicable to the situation that contains reference data types such as NaN, array, and object.
includes
function unique(sourceData) {
let filterArray = []
sourceData.forEach(item => {
if (!filterArray.includes(item)) {
filterArray.push(item)
}
})
return filterArray
}
// [[], [], 34, 6, "6", NaN, {}, {}, "a", "f", false, null, true, undefined]
reduce
function unique(sourceData = []) {
return sourceData.reduce((pre, cur) => pre.includes(cur) ? pre : [...pre, cur], [])
}
// [[], [], 34, 6, "6", NaN, {}, {}, "a", "f", false, null, true, undefined]
map
function unique(sourceData) {
let map = new Map() // 创建Map实例
return sourceData.filter(item => {
return !map.has(item) && map.set(item, 1)
})
}
// [[], [], 34, 6, "6", NaN, {}, {}, "a", "f", false, null, true, undefined]
set
function unique10(sourceData) {
return [...new Set(sourceData)]
}
// [[], [], 34, 6, "6", NaN, {}, {}, "a", "f", false, null, true, undefined]
Note: The above schemes are not suitable for situations that contain reference data types such as arrays and objects.
object
Use the uniqueness of object attributes to remove duplicates.
function unique(sourceData) {
let map = new Map() // 创建Map实例
let filterArray = []
for (let i = 0; i < sourceData.length; i++) {
/**
* 为什么要使用JSON.stringify()
* typeof sourceData[i] + sourceData[i] 拼接字符串时可能存在[object Object]
*/
if (!map[typeof sourceData[i] + JSON.stringify(sourceData[i])]) {
map[typeof sourceData[i] + JSON.stringify(sourceData[i])] = true;
filterArray.push(sourceData[i]);
}
}
return filterArray
}
// [[], 34, 6, "6", NaN, {}, "a", "f", false, null, true, undefined]
Randomly generated 10,000 sets of digital data, and the execution time according to the order of the above code is as follows:
To summarize: the shorter time-consuming set
map
sort
, the longer time-consuming reduce
object
scheme can handle reference data types.
Array flattening
The test data of array flattening is as follows:
const sourceArray = [4, '4', ['c', 6], {}, [7, ['v']], ['s', [6, 23, ['叹郁孤']]]]
concat + recursion
function flat(sourceArray, flatArray) {
sourceArray.forEach(item => {
Array.isArray(item) ? flatArray.concat(flat(item, flatArray)) : flatArray.push(item)
});
return flatArray
}
const flatArray = flat(sourceArray, [])
// [4, "4", "c", 6, {…}, 7, "v", "s", 6, 23, "叹郁孤"]
... + recursion
function flat(sourceArray) {
while (sourceArray.some(item => Array.isArray(item))) {
sourceArray = [].concat(...sourceArray);
}
return sourceArray;
}
const flatArray = flat(sourceArray)
// [4, "4", "c", 6, {…}, 7, "v", "s", 6, 23, "叹郁孤"]
reduce + recursion
function flat(sourceArray) {
return sourceArray.reduce((pre, cur) => pre.concat(Array.isArray(cur) ? flat3(cur) : cur), [])
}
const flatArray = flat(sourceArray)
// [4, "4", "c", 6, {…}, 7, "v", "s", 6, 23, "叹郁孤"]
flat
function flat(sourceArray) {
/**
* flat参数说明
* 默认:flag() 数组只展开一层
* 数字:flat(2) 数组展开两层,传入控制展开层数的数字;数字小于等于0,返回原数组
* Infinity:flat(Infinity),展开成一维数组
*/
return sourceArray.flat(Infinity)
}
const flatArray = flat(sourceArray)
// [4, "4", "c", 6, {…}, 7, "v", "s", 6, 23, "叹郁孤"]
Array union
The test data of array union, intersection, and difference are as follows:
const sourceArray = [
48, 34, '6', undefined, 'f', 'a',
34, true, NaN, false, 34, true, 'f'
]
const sourceArray2 = [
52, 34, '6', undefined, 's', 23,
'cf', true, NaN, false, NaN
]
filter + includes
function union(sourceArray, sourceArray2) {
const unionArray = sourceArray.concat(sourceArray2.filter(item => !sourceArray.includes(item)))
return [...new Set(unionArray)]
}
const unionArray = union(sourceArray, sourceArray2)
// [48, 34, "6", undefined, "f", "a", true, NaN, false, 52, "s", 23, "cf"]
set
function union(sourceArray, sourceArray2) {
return [...new Set([...sourceArray, ...sourceArray2])]
}
const unionArray = union(sourceArray, sourceArray2)
// [48, 34, "6", undefined, "f", "a", true, NaN, false, 52, "s", 23, "cf"]
Array intersection
filter + includes
function intersect(sourceArray, sourceArray2) {
const intersectArray = sourceArray.filter(item => sourceArray2.includes(item))
return [...new Set(intersectArray)]
}
const intersectArray = intersect(sourceArray, sourceArray2)
// [34, "6", undefined, true, NaN, false]
set
function intersect(sourceArray, sourceArray2) {
sourceArray = new Set(sourceArray)
sourceArray2 = new Set(sourceArray2)
const intersectArray = [...sourceArray].filter(item => sourceArray2.has(item))
return [...new Set(intersectArray)]
}
const intersectArray = intersect(sourceArray, sourceArray2)
// [34, "6", undefined, true, NaN, false]
Array subtraction
filter + includes
function difference(sourceArray, sourceArray2) {
const differenceArray = sourceArray.concat(sourceArray2)
.filter(item => !sourceArray2.includes(item))
return [...new Set(differenceArray)]
}
const differenceArray = difference(sourceArray, sourceArray2)
// [48, "f", "a"]
set
function difference(sourceArray, sourceArray2) {
sourceArray = new Set(sourceArray)
sourceArray2 = new Set(sourceArray2)
const intersectArray = [...sourceArray].filter(item => !sourceArray2.has(item))
return [...new Set(intersectArray)]
}
const differenceArray = difference(sourceArray, sourceArray2)
// [48, "f", "a"]
Array partition
The array split test data is as follows:
const sourceArray = [73, 343, 'g', 56, 'j', 10, 32, 43, 90, 'z', 9, 4, 28, 'z', 58, 78, 'h']
const chunkArray = chunk(sourceArray, 4)
while + slice
function chunk(sourceArray = [], length = 1) {
let chunkArray = []
let index = 0
while (index < sourceArray.length) {
chunkArray.push(sourceArray.slice(index, index += length))
}
return chunkArray
}
const chunkArray = chunk(sourceArray, 4)
// [[73, 343, "g", 56], ["j", 10, 32, 43], [90, "z", 9, 4], [28, "z", 58, 78], ["h"]]
reduce
The following are 25 advanced usages of array reduce The array partition method of this article may not be easy to understand at first glance. I slightly changed the code knot and added comments for easy understanding. The original code is as follows:
function chunk(arr = [], size = 1) {
return arr.length ? arr.reduce((t, v) => (t[t.length - 1].length === size ? t.push([v]) : t[t.length - 1].push(v), t), [[]]) : [];
}
Adjusted code:
function chunk(arr = [], size = 1) {
if (arr.length) {
arr = arr.reduce((t, v) => {
/**
* t的初始值为[[]],这时t.length为1,所以t[t.length - 1]为[],t[t.length - 1].length为0,将v push到t[0]中,此时t = [[73]]
* 这时t.length还是为1,所以t[t.length - 1]为[73],t[t.length - 1].length为1,将v push到t[0]中,此时t = [[73, 343]]
* 直到t[0]有四个数据后[[73, 343, "g", 56]]
* 这时t.length为1,所以t[t.length - 1]为[73, 343, "g", 56],t[t.length - 1].length为4,将[v] push到t中,此时t = [[73, 343, "g", 56]['j']],以此类推
*/
t[t.length - 1].length === size ? t.push([v]) : t[t.length - 1].push(v)
return t
}, [[]])
}
return arr
}
// [[73, 343, "g", 56], ["j", 10, 32, 43], [90, "z", 9, 4], [28, "z", 58, 78], ["h"]]
Array to object
Object.assign
const sourceArray = ['CSS世界', '活着', '资本论']
function toObject(sourceArray) {
return Object.assign({}, sourceArray)
}
const result = toObject(sourceArray)
// {0: "CSS世界", 1: "活着", 2: "资本论"}
reduce
The first object form
const books = [
{ name: "CSS世界", author: "张鑫旭", price: 69, serialNumber: 'ISBN: 97871151759' },
{ name: "活着", author: "余华", price: 17.5, serialNumber: 'I247.57/105' },
{ name: "资本论", author: "马克思", price: 75, serialNumber: '9787010041155' }
];
function toObject(books) {
return books.reduce((pre, cur) => {
/**
* ...rest用于获取剩余的解构数据
* 如:{ name: "CSS世界", author: "张鑫旭", price: 69 }
*/
const { serialNumber, ...rest } = cur;
pre[serialNumber] = rest;
return pre;
}, {});
}
const map = toObject(books)
/**
* {
* ISBN: 97871151759: {name: "CSS世界", author: "张鑫旭", price: 69},
* I247.57/105: {name: "活着", author: "余华", price: 17.5},
* 9787010041155: {name: "资本论", author: "马克思", price: 75}
* }
*/
The second object form
// 方案一
const person = [
{ name: "Siri", age: 22 },
{ name: "Bob", age: 20 },
{ name: "Tom", age: 21 }
];
function toObject(person) {
return person.reduce((pre, cur) => (pre[cur.name] = cur.age, pre), {})
}
const result = toObject(person)
// {Siri: 22, Bob: 20, Tom: 21}
// 方案二
function toObject2(person) {
return person.reduce((pre, cur) => ({...pre, [cur.name]: cur.age}), {})
}
const result = toObject2(person)
// {Siri: 22, Bob: 20, Tom: 21}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。