JavaScript/array:修订间差异
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” 标签:ReplaceText 移动版编辑 移动版网页编辑 |
|||
| (未显示同一用户的24个中间版本) | |||
| 第9行: | 第9行: | ||
{| class="wikitable" | {| class="wikitable" | ||
|- | |- | ||
| [[/find|find]] || [[/forEach|forEach]] || [[/map|map]] | | [[/find|find]] || [[/forEach|forEach]] || [[/map|map]] || [[/reduce|reduce]] | ||
|- | |- | ||
| [[/every|every]] || [[/some|some]] || [[/filter|filter]] | | [[/every|every]] || [[/some|some]] || [[/filter|filter]] | ||
| 第20行: | 第20行: | ||
=== 示例 === | === 示例 === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
Object.keys(['a',, 'c']);</syntaxhighlight>|{{consoleout|<pre> | Object.keys(['a',, 'c']);</syntaxhighlight>|{{consoleout|<pre> | ||
['0', '2'] | ['0', '2'] | ||
| 第27行: | 第27行: | ||
== 创建数组 == | == 创建数组 == | ||
=== new === | === new === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
new Array(3); | new Array(3); | ||
// or | // or | ||
| 第33行: | 第33行: | ||
[空属性 × 3] | [空属性 × 3] | ||
[0, 1, 2] | [0, 1, 2] | ||
</pre>}}}} | |||
==== 应用 ==== | |||
生成所有的英文字母 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
[...new Array(26)].map((_, i) => String.fromCharCode(65 + i)); | |||
[...new Array(26)].map((_, i) => String.fromCharCode(97 + i));</syntaxhighlight>|{{consoleout|<pre> | |||
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] | |||
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] | |||
</pre>}}}} | </pre>}}}} | ||
=== copyWithin === | === copyWithin === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
[...new Array(5)].map((_, i) => i).copyWithin(3); | [...new Array(5)].map((_, i) => i).copyWithin(3); | ||
// or | // or | ||
| 第45行: | 第54行: | ||
=== apply === | === apply === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
Array.apply(null, Array(3)); | Array.apply(null, Array(3)); | ||
// or | // or | ||
| 第54行: | 第63行: | ||
[undefined, undefined, undefined] | [undefined, undefined, undefined] | ||
[0, 1, 2] | [0, 1, 2] | ||
</pre>}}}} | |||
=== of === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
Array.of(1, 2, 3);</syntaxhighlight>|{{consoleout|<pre> | |||
[1, 2, 3] | |||
</pre>}}}} | |||
=== ArrayBuffer === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
new ArrayBuffer(8);</syntaxhighlight>|{{consoleout|<pre> | |||
ArrayBuffer(8) | |||
byteLength: 8 | |||
[[Prototype]]: ArrayBuffer | |||
[[Int8Array]]: Int8Array(8) | |||
[[Uint8Array]]: Uint8Array(8) | |||
[[Int16Array]]: Int16Array(4) | |||
[[Int32Array]]: Int32Array(2) | |||
[[ArrayBufferByteLength]]: 8 | |||
[[ArrayBufferData]]: 258 | |||
</pre>}}}} | </pre>}}}} | ||
=== Array.from === | === Array.from === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
Array.from( | Array.from( | ||
{length: 3}, | {length: 3}, | ||
| 第69行: | 第98行: | ||
=== fill === | === fill === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
new Array(3).fill('kangkk');</syntaxhighlight>|{{consoleout|<pre> | new Array(3).fill('kangkk');</syntaxhighlight>|{{consoleout|<pre> | ||
['kangkk', 'kangkk', 'kangkk'] | ['kangkk', 'kangkk', 'kangkk'] | ||
</pre>}}}} | </pre>}}}} | ||
创建一个二维数组,如果使用 fill 创建,会遇到一个很经典的引用问题。fill 填充的是相同的引用。 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const arr = new Array(3).fill(new Array(3).fill(0));</syntaxhighlight>|{{consoleout|<pre>(3) [Array(3), Array(3), Array(3)] | |||
0: (3) [0, 0, 0] | |||
1: (3) [0, 0, 0] | |||
2: (3) [0, 0, 0] | |||
</pre>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
arr[0][1] = 9</syntaxhighlight>|{{consoleout|<pre> | |||
(3) [Array(3), Array(3), Array(3)] | |||
0: (3) [0, 9, 0] | |||
1: (3) [0, 9, 0] | |||
2: (3) [0, 9, 0] | |||
</pre>}}}} | |||
稍微变通一下 | |||
<syntaxhighlight lang="javascript"> | |||
Array.apply(null, Array(3)).map(_ => new Array(3).fill(0))</syntaxhighlight> | |||
== 插入 == | == 插入 == | ||
| 第78行: | 第128行: | ||
== 合并 == | == 合并 == | ||
合并两个数组。 | 合并两个数组。 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
const source = [1, 2]; | const source = [1, 2]; | ||
const target = [3, 4]; | const target = [3, 4]; | ||
| 第110行: | 第160行: | ||
=== splice === | === splice === | ||
删除。 | 删除。 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
const foo = ['a', 'b', 'c', 'd', 'e']; | const foo = ['a', 'b', 'c', 'd', 'e']; | ||
const bar = foo.splice(1, 2); | const bar = foo.splice(1, 2); | ||
| 第119行: | 第169行: | ||
</pre>}}}} | </pre>}}}} | ||
替换。 | 替换。 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
const foo = ['a', 'b', 'c', 'd', 'e']; | const foo = ['a', 'b', 'c', 'd', 'e']; | ||
const bar = foo.splice(1, 2, 'f'); | const bar = foo.splice(1, 2, 'f'); | ||
| 第128行: | 第178行: | ||
</pre>}}}} | </pre>}}}} | ||
添加。 | 添加。 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
const foo = ['a', 'b', 'c', 'd', 'e']; | const foo = ['a', 'b', 'c', 'd', 'e']; | ||
const bar = foo.splice(1, 0, 'f'); | const bar = foo.splice(1, 0, 'f'); | ||
| 第137行: | 第187行: | ||
</pre>}}}} | </pre>}}}} | ||
=== delete === | === delete === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
const foo = ['a', 'b', 'c', 'd', 'e']; | const foo = ['a', 'b', 'c', 'd', 'e']; | ||
delete foo[2]; | delete foo[2]; | ||
| 第144行: | 第194行: | ||
</pre>}}}} | </pre>}}}} | ||
=== concat === | === concat === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
Array.prototype.del = function (n) { | Array.prototype.del = function (n) { | ||
if(n < 0) return this; | if(n < 0) return this; | ||
| 第161行: | 第211行: | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
if (!this.length || this.length == 0) return this;</syntaxhighlight> | if (!this.length || this.length == 0) return this;</syntaxhighlight> | ||
== 排序 == | |||
=== 字符串排序 === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
[ | |||
{name: '康健26'}, {name: '康健'}, {name: '康健1'},{name: '康健19'},{name: '兰倩'},{name: '兰倩3'} | |||
].sort((a, b) => { | |||
return a.name.localeCompare(b.name) | |||
});</syntaxhighlight>|{{consoleout|<pre> | |||
(6) [{…}, {…}, {…}, {…}, {…}, {…}] | |||
0: {name: '康健'} | |||
1: {name: '康健1'} | |||
2: {name: '康健19'} | |||
3: {name: '康健26'} | |||
4: {name: '兰倩'} | |||
5: {name: '兰倩3'} | |||
</pre>}}}} | |||
== 示例 == | == 示例 == | ||
=== 去重 === | === 去重 === | ||
| 第207行: | 第275行: | ||
a - b | a - b | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
function sub(source, target) { | function sub(source, target) { | ||
if ( | if ( | ||
| 第231行: | 第299行: | ||
</pre>}}}} | </pre>}}}} | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
function sub(source, target) { | function sub(source, target) { | ||
if (Array.isArray(source) && Array.isArray(target)) { | if (Array.isArray(source) && Array.isArray(target)) { | ||
| 第243行: | 第311行: | ||
=== 数组取不相同部分 === | === 数组取不相同部分 === | ||
数字单一元素。 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const foo = [6, 4, 7, 12]; | |||
const bar = [1, 5, 6, 9, 3, 4]; | |||
const difference = (source, target) => { | |||
return source.concat(target).filter((v, i, arr) => (arr.indexOf(v) === arr.lastIndexOf(v))); | |||
} | |||
console.log(difference(foo, bar));</syntaxhighlight>|{{consoleout|<pre>7,12,1,5,9,3 | |||
</pre>}}}} | |||
根据不同 key 进行区分。 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const listOfTags = [ | |||
{ id: 1, label: "Hello", color: "red", sorting: 0 }, | |||
{ id: 2, label: "World", color: "green", sorting: 1 }, | |||
{ id: 3, label: "Hello", color: "blue", sorting: 4 }, | |||
{ id: 4, label: "Sunshine", color: "yellow", sorting: 5 }, | |||
{ id: 5, label: "Hello", color: "red", sorting: 6 } | |||
]; | |||
const keys = ['label', 'color']; | |||
const filtered = listOfTags.filter( | |||
( | |||
s => o => | |||
(k => !s.has(k) && s.add(k)) | |||
(keys.map(k => o[k]).join('|')) | |||
) (new Set) | |||
); | |||
console.log(JSON.stringify(filtered));</syntaxhighlight>|{{consoleout|<pre>[ | |||
{"id":1,"label":"Hello","color":"red","sorting":0}, | |||
{"id":2,"label":"World","color":"green","sorting":1}, | |||
{"id":3,"label":"Hello","color":"blue","sorting":4}, | |||
{"id":4,"label":"Sunshine","color":"yellow","sorting":5} | |||
] | |||
</pre>}}}} | |||
{{Unknown|https://stackoverflow.com/questions/15125920/how-to-get-distinct-values-from-an-array-of-objects-in-javascript}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const array = | |||
[ | |||
{ "name": "Joe", "age": 17 }, | |||
{ "name": "Bob", "age": 17 }, | |||
{ "name": "Carl", "age": 35 } | |||
]; | |||
const key = 'age'; | |||
const arrayUniqueByKey = [...new Map(array.map(item => [item[key], item])).values()]; | |||
console.log(JSON.stringify(arrayUniqueByKey));</syntaxhighlight>|{{consoleout|<pre> | |||
[ | |||
{"name":"Bob","age":17}, | |||
{"name":"Carl","age":35} | |||
] | |||
</pre>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const foo = [{id: 1, email: 'a@x.y'}, {id: 2, email: 'b@x.y'}, {id: 3, email: 'c@x.y'}]; | |||
const bar = [{dept_id: 1, email: 'c@x.y'}, {dept_id: 2, email: 'd@x.y'}, {dept_id: 3, email: 'e@x.y'}]; | |||
const values = Object.values( | |||
foo.concat(bar).reduce((a, b) => { | |||
if (!a[b.email]) a[b.email] = b | |||
return a | |||
}, {}) | |||
) | |||
console.log(JSON.stringify(values));</syntaxhighlight>|{{consoleout|<pre> | |||
[ | |||
{"id":1,"email":"a@x.y"}, | |||
{"id":2,"email":"b@x.y"}, | |||
{"id":3,"email":"c@x.y"}, | |||
{"dept_id":2,"email":"d@x.y"}, | |||
{"dept_id":3,"email":"e@x.y"} | |||
] | |||
</pre>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const foo = [{id: 1, email: 'a@x.y'}, {id: 2, email: 'b@x.y'}, {id: 3, email: 'c@x.y'}]; | |||
const bar = [{id: 3, dept_id: 1, email: 'c@x.y'}, {id: 1, dept_id: 2, email: 'd@x.y'}, {id: 5, dept_id: 3, email: 'e@x.y'}]; | |||
const uniques = Object.values( | |||
foo.concat(bar).reduce((a, c) => { | |||
a[c.email + '|' + c.id] = c; | |||
return a | |||
}, {})) | |||
console.log(JSON.stringify(uniques));</syntaxhighlight>|{{consoleout|<pre> | |||
[ | |||
{"id":1,"email":"a@x.y"}, | |||
{"id":2,"email":"b@x.y"}, | |||
{"id":3,"dept_id":1,"email":"c@x.y"}, | |||
{"id":1,"dept_id":2,"email":"d@x.y"}, | |||
{"id":5,"dept_id":3,"email":"e@x.y"} | |||
] | |||
</pre>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
/** | |||
* @param {array} arr The array you want to filter for dublicates | |||
* @param {array<string>} indexedKeys The keys that form the compound key | |||
* which is used to filter dublicates | |||
* @param {boolean} isPrioritizeFormer Set this to true, if you want to remove | |||
* dublicates that occur later, false, if you want those to be removed | |||
* that occur later. | |||
*/ | |||
const distinct = (arr, indexedKeys, isPrioritizeFormer = true) => { | |||
const lookup = new Map(); | |||
const makeIndex = el => indexedKeys.reduce( | |||
(index, key) => `${index};;${el[key]}`, '' | |||
); | |||
arr.forEach(el => { | |||
const index = makeIndex(el); | |||
if (lookup.has(index) && isPrioritizeFormer) { | |||
return; | |||
} | |||
lookup.set(index, el); | |||
}); | |||
return Array.from(lookup.values()); | |||
};</syntaxhighlight>|{{consoleout|<pre> | |||
</pre>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const keys = ['label', 'color'], | |||
const mySet = new Set(); | |||
const duplicateSet = new Set(); | |||
const result = objList.filter((item) => { | |||
let newItem = keys.map((k) => item[k]).join("-"); | |||
mySet.has(newItem) && duplicateSet.add(newItem); | |||
return !mySet.has(newItem) && mySet.add(newItem); | |||
}); | |||
console.log(duplicateSet, result);</syntaxhighlight>|{{consoleout|<pre> | |||
</pre>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const source = [{id: 1, email: 'a@x.y'}, {id: 2, email: 'b@x.y'}, {id: 3, email: 'c@x.y'}]; | |||
const target = [{dept_id: 1, email: 'c@x.y'}, {dept_id: 2, email: 'd@x.y'}, {dept_id: 3, email: 'e@x.y'}]; | |||
const map = new Map(); | |||
const newUser = source.filter(_ => { | |||
const item = target.find(({email}) => email === _.email); | |||
if (item && !map.has(_.email)) map.set(_.email, item); | |||
return !item | |||
}); | |||
const deleteUser = target.filter(_ => { | |||
const item = source.find(({email}) => email === _.email); | |||
if (item && map.has(_.email) && JSON.stringify(map.get(_.email)) === JSON.stringify(item)) map.delete(_.email); | |||
return !item | |||
}); | |||
console.log(JSON.stringify(newUser)); | |||
console.log(JSON.stringify(deleteUser)); | |||
console.log([...map.values()]);</syntaxhighlight>|{{consoleout|<pre> | |||
[{"id":1,"email":"a@x.y"},{"id":2,"email":"b@x.y"}] | |||
[{"dept_id":2,"email":"d@x.y"},{"dept_id":3,"email":"e@x.y"}] | |||
[{ dept_id: 1, email: 'c@x.y' }] | |||
</pre>}}}} | |||
=== 数组交集 === | |||
=== 数组拍平 === | === 数组拍平 === | ||
| 第249行: | 第471行: | ||
const sample = [1, 2, [3, 4, 5, [6, 7, 8], 9], 10, [11, 12]];</syntaxhighlight> | const sample = [1, 2, [3, 4, 5, [6, 7, 8], 9], 10, [11, 12]];</syntaxhighlight> | ||
递归。 | 递归。 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
function clap(arr){ | function clap(arr){ | ||
let cup = []; | let cup = []; | ||
| 第269行: | 第491行: | ||
reduce。 | reduce。 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
function clap(arr){ | function clap(arr){ | ||
return arr.reduce((prev, cur)=>{ | return arr.reduce((prev, cur)=>{ | ||
| 第283行: | 第505行: | ||
flat。 | flat。 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
function clap(arr){ | function clap(arr){ | ||
return arr.flat(Infinity); | return arr.flat(Infinity); | ||
| 第295行: | 第517行: | ||
扩展运算符。有待优化。 | 扩展运算符。有待优化。 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
function clap(arr){ | function clap(arr){ | ||
let cup = []; | let cup = []; | ||
| 第318行: | 第540行: | ||
toString。 | toString。 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
function clap(arr){ | function clap(arr){ | ||
return arr.toString().split(',').map(_ => parseInt(_)); | return arr.toString().split(',').map(_ => parseInt(_)); | ||
| 第330行: | 第552行: | ||
apply。 | apply。 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
function clap(arr){ | function clap(arr){ | ||
while(arr.some(_ => Array.isArray(_))){ | while(arr.some(_ => Array.isArray(_))){ | ||
| 第346行: | 第568行: | ||
== 清空数组 == | == 清空数组 == | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
var arr = [0, 1, 2, 3]; | var arr = [0, 1, 2, 3]; | ||
var obj = {val: arr}; | var obj = {val: arr}; | ||
| 第355行: | 第577行: | ||
清空数组 | 清空数组 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
var arr = [0, 1, 2, 3]; | var arr = [0, 1, 2, 3]; | ||
var obj = {val: arr}; | var obj = {val: arr}; | ||
| 第368行: | 第590行: | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
...new Set(array)</syntaxhighlight> | ...new Set(array)</syntaxhighlight> | ||
{{ | {{Double-columns|<syntaxhighlight | ||
lang="javascript"> | lang="javascript"> | ||
console.log([...new Set([1, 2, 1, 1, '1'])]) | console.log([...new Set([1, 2, 1, 1, '1'])]) | ||
| 第375行: | 第597行: | ||
</pre>}}}} | </pre>}}}} | ||
接着试探着问面试官应该可以吧,面试官反应平平(我猜测他可能没用过这种方式,也不知道对不对),我也不好再尝试运行,虽然我知道可以解这道题,但是面试官不确定那我还是老老实实写其他代码吧,然后写了如下: | 接着试探着问面试官应该可以吧,面试官反应平平(我猜测他可能没用过这种方式,也不知道对不对),我也不好再尝试运行,虽然我知道可以解这道题,但是面试官不确定那我还是老老实实写其他代码吧,然后写了如下: | ||
{{ | {{Double-columns|<syntaxhighlight | ||
lang="javascript"> | lang="javascript"> | ||
function foo(arr){ | function foo(arr){ | ||
| 第397行: | 第619行: | ||
面试官说你看对么,然后我看了一眼发现 <code>Number 1</code> 和 <code>String 1</code> 被等值了,毕竟是 map 是一个 object。我又尝试的问了一下,您觉的这样应该怎么处理呢,面试官说:“你在里面加一下判断,试着把 <code>Number 1</code> 和 <code>String 1</code> 区分开”,我想了一下没什么概念就试探着说其实这里可以用 Map 解决的,只需要把 <code>var map = new Map()</code> 就可以了(我感觉没有我反应快。。。,而且这判断怎么加。。。),面试官无感,我也就没再改代码,然后结束了。事后补全以下代码: | 面试官说你看对么,然后我看了一眼发现 <code>Number 1</code> 和 <code>String 1</code> 被等值了,毕竟是 map 是一个 object。我又尝试的问了一下,您觉的这样应该怎么处理呢,面试官说:“你在里面加一下判断,试着把 <code>Number 1</code> 和 <code>String 1</code> 区分开”,我想了一下没什么概念就试探着说其实这里可以用 Map 解决的,只需要把 <code>var map = new Map()</code> 就可以了(我感觉没有我反应快。。。,而且这判断怎么加。。。),面试官无感,我也就没再改代码,然后结束了。事后补全以下代码: | ||
{{ | {{Double-columns|<syntaxhighlight | ||
lang="javascript"> | lang="javascript"> | ||
function foo(arr){ | function foo(arr){ | ||
| 第465行: | 第687行: | ||
// if ((item.name?.indexOf(searchValue) != -1)) return 1 === 1; | // if ((item.name?.indexOf(searchValue) != -1)) return 1 === 1; | ||
});</syntaxhighlight> | });</syntaxhighlight> | ||
== 数组对象 == | |||
=== 数组取差值 === | |||
已知两个数组,source 为 输入数组,target 为目标存储的数组,通过原子 key 进行存储的数组的值的插入更新和删除操作。 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const source = [ | |||
{id: 1, name: 'bob', age: 18}, | |||
{id: 5, name: 'lili'}, | |||
{id: 8, name: 'lilei', photo: 'htpp://image'} | |||
]; | |||
const target = [ | |||
{id: 5, name: 'lili'}, | |||
{id: 1, name: 'bob', age: 20}, | |||
{id: 10, name: 'xiaoming', age: 27, photo: 'htpp://image'} | |||
]; | |||
const checkUser = (source, target, key) => { | |||
const map = new Map(); | |||
const newUser = source.filter(_ => { | |||
const item = target.find($ => $[key] === _[key]); | |||
if (item && !map.has(_[key])) map.set(_[key], item); | |||
return !item; | |||
}); | |||
const deleteUser = target.filter(_ => { | |||
const item = source.find($ => $[key] === _[key]); | |||
if (item && map.has(_[key]) && JSON.stringify(map.get(_[key])) === JSON.stringify(item)) map.delete(_[key]); | |||
return !item; | |||
}); | |||
const updateUser = [...map.values()]; | |||
return { | |||
add: newUser, | |||
update: updateUser, | |||
delete: deleteUser | |||
}; | |||
} | |||
const result = checkUser(source, target, 'id'); | |||
console.log(result); | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
{ | |||
add: [ { id: 8, name: 'lilei', photo: 'htpp://image' } ], | |||
update: [ { id: 1, name: 'bob', age: 20 } ], | |||
delete: [ { id: 10, name: 'xiaoming', age: 27, photo: 'htpp://image' } ] | |||
} | |||
</pre>}}}} | |||
一个变体,用来判断是否和如何更新数据库的内容。 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const source = [ | |||
{mail: 'bob@x.y', name: 'bob', age: 18}, | |||
{mail: 'lili@x.y', name: 'lili'}, | |||
{mail: 'lilei@x.y', name: 'lilei', photo: 'htpp://image'} | |||
]; | |||
const target = [ | |||
{id: 5, mail: 'lili@x.y', name: 'lili'}, | |||
{id: 1, mail: 'bob@x.y', name: 'bob', age: 20}, | |||
{id: 10, mail: 'xiaoming@x.y', name: 'xiaoming', age: 27, photo: 'htpp://image'} | |||
]; | |||
const checkUser = (source, target, key, id) => { | |||
const map = new Map(); | |||
const newUser = source.filter(_ => { | |||
const item = target.find($ => $[key] === _[key]); | |||
if (item && !map.has(_[key])) map.set(_[key], item); | |||
return !item; | |||
}); | |||
const deleteUser = target.filter(_ => { | |||
const item = source.find($ => $[key] === _[key]); | |||
if (item && map.has(_[key])) { | |||
const {[id]: _id, ...data} = map.get(_[key]); | |||
if (JSON.stringify(data) === JSON.stringify(item)) map.delete(_[key]); | |||
else map.set(_[key], {[id]: _id, ...item}); | |||
} | |||
return !item; | |||
}); | |||
const updateUser = [...map.values()]; | |||
return { | |||
add: newUser, | |||
update: updateUser, | |||
delete: deleteUser | |||
}; | |||
} | |||
const result = checkUser(source, target, 'mail', 'id'); | |||
console.log(result);</syntaxhighlight>|{{consoleout|<pre>{ | |||
add: [ { mail: 'lilei@x.y', name: 'lilei', photo: 'htpp://image' } ], | |||
update: [ { id: 1, mail: 'bob@x.y', name: 'bob', age: 18 } ], | |||
delete: [ | |||
{ | |||
id: 10, | |||
mail: 'xiaoming@x.y', | |||
name: 'xiaoming', | |||
age: 27, | |||
photo: 'htpp://image' | |||
} | |||
] | |||
} | |||
</pre>}}}} | |||
== 参考 == | == 参考 == | ||
* [https://v8.dev/blog/elements-kinds Elements kinds in V8] | * [https://v8.dev/blog/elements-kinds Elements kinds in V8] | ||
2026年11月26日 (四) 09:55的最新版本
引言
特点
- 相同的数据类型
- 连续的线性内存
稀疏数组
有空值的数组。
方法
| find | forEach | map | reduce |
| every | some | filter | |
| indexOf | reverse | 解构... |
holes
数组空洞(缺失索引)[1]。
示例
Object.keys(['a',, 'c']);
['0', '2']
创建数组
new
new Array(3);
// or
[...new Array(3)].map((_, i) => i);
[空属性 × 3] [0, 1, 2]
应用
生成所有的英文字母
[...new Array(26)].map((_, i) => String.fromCharCode(65 + i));
[...new Array(26)].map((_, i) => String.fromCharCode(97 + i));
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
copyWithin
[...new Array(5)].map((_, i) => i).copyWithin(3);
// or
[...new Array(5)].map((_, i) => i).copyWithin(2, 3, 4);
[0, 1, 2, 0, 1] [0, 1, 3, 3, 4]
apply
Array.apply(null, Array(3));
// or
Array.apply(null, [, , ,]);
// or
Array.apply(null, Array(3)).map((_, i) => i);
[undefined, undefined, undefined] [undefined, undefined, undefined] [0, 1, 2]
of
Array.of(1, 2, 3);
[1, 2, 3]
ArrayBuffer
new ArrayBuffer(8);
ArrayBuffer(8) byteLength: 8 [[Prototype]]: ArrayBuffer [[Int8Array]]: Int8Array(8) [[Uint8Array]]: Uint8Array(8) [[Int16Array]]: Int16Array(4) [[Int32Array]]: Int32Array(2) [[ArrayBufferByteLength]]: 8 [[ArrayBufferData]]: 258
Array.from
Array.from(
{length: 3},
(_v, k) => k
);
// or
Array.from(new Array(3).keys());
[0, 1, 2] [0, 1, 2]
fill
new Array(3).fill('kangkk');
['kangkk', 'kangkk', 'kangkk']
创建一个二维数组,如果使用 fill 创建,会遇到一个很经典的引用问题。fill 填充的是相同的引用。
const arr = new Array(3).fill(new Array(3).fill(0));
(3) [Array(3), Array(3), Array(3)] 0: (3) [0, 0, 0] 1: (3) [0, 0, 0] 2: (3) [0, 0, 0]
arr[0][1] = 9
(3) [Array(3), Array(3), Array(3)] 0: (3) [0, 9, 0] 1: (3) [0, 9, 0] 2: (3) [0, 9, 0]
稍微变通一下
Array.apply(null, Array(3)).map(_ => new Array(3).fill(0))
插入
合并
合并两个数组。
const source = [1, 2];
const target = [3, 4];
const lastItem = source.push.apply(source, target || []);
console.log(lastItem);
console.log(source);
4 [1, 2, 3, 4]
交换
第三方变量
const temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
splice
array.splice(index2,1,...array.splice(index1, 1 , array[index2]));
解构赋值
[array[index1],array[index2]] = [array[index2],array[index1]];
查找
优化
二分法
O(log n)
删除
splice
删除。
const foo = ['a', 'b', 'c', 'd', 'e'];
const bar = foo.splice(1, 2);
console.log(foo);
console.log(bar);
['a', 'd', 'e'] ['b', 'c']
替换。
const foo = ['a', 'b', 'c', 'd', 'e'];
const bar = foo.splice(1, 2, 'f');
console.log(foo);
console.log(bar);
[ 'a', 'f', 'd', 'e' ] [ 'b', 'c' ]
添加。
const foo = ['a', 'b', 'c', 'd', 'e'];
const bar = foo.splice(1, 0, 'f');
console.log(foo);
console.log(bar);
[ 'a', 'f', 'b', 'c', 'd', 'e' ] []
delete
const foo = ['a', 'b', 'c', 'd', 'e'];
delete foo[2];
console.log(foo);
[ 'a', 'b', <1 empty item>, 'd', 'e' ]
concat
Array.prototype.del = function (n) {
if(n < 0) return this;
else return this.slice(0, n).concat(this.slice(n + 1, this.length));
}
const foo = new Array('a', 'b', 'c', 'd', 'e');
foo.del(3);
console.log(foo);
[ 'a', 'b', 'c', 'd', 'e' ]
读取
遍历
判断
if (!this.length || this.length == 0) return this;
排序
字符串排序
[
{name: '康健26'}, {name: '康健'}, {name: '康健1'},{name: '康健19'},{name: '兰倩'},{name: '兰倩3'}
].sort((a, b) => {
return a.name.localeCompare(b.name)
});
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {name: '康健'}
1: {name: '康健1'}
2: {name: '康健19'}
3: {name: '康健26'}
4: {name: '兰倩'}
5: {name: '兰倩3'}
示例
去重
Array.prototype.uniq = function () {
if (!this.length || this.length == 0) return this;
var res = [], key, hasNaN = false, temp = {};
for (var i = 0 ; i < this.length; i++) {
if (typeof this[i] === 'object') {
res.push(this[i]);
} else if (this[i] != this[i]) { // 如果当前遍历元素是NaN
if (!hasNaN) {
res.push(this[i]);
hasNaN = true;
}
} else {
key = typeof(this[i]) + this[i];
if (!temp[key]) {
res.push(this[i]);
temp[key] = true;
}
}
}
return res;
}
Array.prototype.uniq = function () {
var res = [];
var flag = true;
this.forEach(function(x) {
if (res.indexOf(x) == -1) {
if (x != x) {
if (flag) {
res.push(x);
flag = false;
}
} else {
res.push(x);
}
}
})
return res;
}
数组相减
a - b
function sub(source, target) {
if (
!source
|| !target
|| Object.prototype.toString.call(source) !== "[object Array]"
|| Object.prototype.toString.call(target) !== "[object Array]"
) {
throw new new TypeError("arguments must be array")();
}
for (var i = 0, len = target.length; i < len; i++) {
for (var j = 0, jen = source.length; j < jen; j++) {
if (source[j] === target[i]) {
source.splice(j, 1);
j--;
}
}
}
return source;
}
console.log(sub([1, 2, 3, 4], [3, 4]));
[ 1, 2 ]
function sub(source, target) {
if (Array.isArray(source) && Array.isArray(target)) {
return source.filter((i) => !target.includes(i));
}
throw new new TypeError("arguments must be array")();
}
console.log(sub([1, 2, 3, 4], [3, 4]));
[ 1, 2 ]
数组取不相同部分
数字单一元素。
const foo = [6, 4, 7, 12];
const bar = [1, 5, 6, 9, 3, 4];
const difference = (source, target) => {
return source.concat(target).filter((v, i, arr) => (arr.indexOf(v) === arr.lastIndexOf(v)));
}
console.log(difference(foo, bar));
7,12,1,5,9,3
根据不同 key 进行区分。
const listOfTags = [
{ id: 1, label: "Hello", color: "red", sorting: 0 },
{ id: 2, label: "World", color: "green", sorting: 1 },
{ id: 3, label: "Hello", color: "blue", sorting: 4 },
{ id: 4, label: "Sunshine", color: "yellow", sorting: 5 },
{ id: 5, label: "Hello", color: "red", sorting: 6 }
];
const keys = ['label', 'color'];
const filtered = listOfTags.filter(
(
s => o =>
(k => !s.has(k) && s.add(k))
(keys.map(k => o[k]).join('|'))
) (new Set)
);
console.log(JSON.stringify(filtered));
[
{"id":1,"label":"Hello","color":"red","sorting":0},
{"id":2,"label":"World","color":"green","sorting":1},
{"id":3,"label":"Hello","color":"blue","sorting":4},
{"id":4,"label":"Sunshine","color":"yellow","sorting":5}
]
(来源摘自互联网示例,作者 https://stackoverflow.com/questions/15125920/how-to-get-distinct-values-from-an-array-of-objects-in-javascript)
const array =
[
{ "name": "Joe", "age": 17 },
{ "name": "Bob", "age": 17 },
{ "name": "Carl", "age": 35 }
];
const key = 'age';
const arrayUniqueByKey = [...new Map(array.map(item => [item[key], item])).values()];
console.log(JSON.stringify(arrayUniqueByKey));
[
{"name":"Bob","age":17},
{"name":"Carl","age":35}
]
const foo = [{id: 1, email: 'a@x.y'}, {id: 2, email: 'b@x.y'}, {id: 3, email: 'c@x.y'}];
const bar = [{dept_id: 1, email: 'c@x.y'}, {dept_id: 2, email: 'd@x.y'}, {dept_id: 3, email: 'e@x.y'}];
const values = Object.values(
foo.concat(bar).reduce((a, b) => {
if (!a[b.email]) a[b.email] = b
return a
}, {})
)
console.log(JSON.stringify(values));
[
{"id":1,"email":"a@x.y"},
{"id":2,"email":"b@x.y"},
{"id":3,"email":"c@x.y"},
{"dept_id":2,"email":"d@x.y"},
{"dept_id":3,"email":"e@x.y"}
]
const foo = [{id: 1, email: 'a@x.y'}, {id: 2, email: 'b@x.y'}, {id: 3, email: 'c@x.y'}];
const bar = [{id: 3, dept_id: 1, email: 'c@x.y'}, {id: 1, dept_id: 2, email: 'd@x.y'}, {id: 5, dept_id: 3, email: 'e@x.y'}];
const uniques = Object.values(
foo.concat(bar).reduce((a, c) => {
a[c.email + '|' + c.id] = c;
return a
}, {}))
console.log(JSON.stringify(uniques));
[
{"id":1,"email":"a@x.y"},
{"id":2,"email":"b@x.y"},
{"id":3,"dept_id":1,"email":"c@x.y"},
{"id":1,"dept_id":2,"email":"d@x.y"},
{"id":5,"dept_id":3,"email":"e@x.y"}
]
/**
* @param {array} arr The array you want to filter for dublicates
* @param {array<string>} indexedKeys The keys that form the compound key
* which is used to filter dublicates
* @param {boolean} isPrioritizeFormer Set this to true, if you want to remove
* dublicates that occur later, false, if you want those to be removed
* that occur later.
*/
const distinct = (arr, indexedKeys, isPrioritizeFormer = true) => {
const lookup = new Map();
const makeIndex = el => indexedKeys.reduce(
(index, key) => `${index};;${el[key]}`, ''
);
arr.forEach(el => {
const index = makeIndex(el);
if (lookup.has(index) && isPrioritizeFormer) {
return;
}
lookup.set(index, el);
});
return Array.from(lookup.values());
};
const keys = ['label', 'color'],
const mySet = new Set();
const duplicateSet = new Set();
const result = objList.filter((item) => {
let newItem = keys.map((k) => item[k]).join("-");
mySet.has(newItem) && duplicateSet.add(newItem);
return !mySet.has(newItem) && mySet.add(newItem);
});
console.log(duplicateSet, result);
const source = [{id: 1, email: 'a@x.y'}, {id: 2, email: 'b@x.y'}, {id: 3, email: 'c@x.y'}];
const target = [{dept_id: 1, email: 'c@x.y'}, {dept_id: 2, email: 'd@x.y'}, {dept_id: 3, email: 'e@x.y'}];
const map = new Map();
const newUser = source.filter(_ => {
const item = target.find(({email}) => email === _.email);
if (item && !map.has(_.email)) map.set(_.email, item);
return !item
});
const deleteUser = target.filter(_ => {
const item = source.find(({email}) => email === _.email);
if (item && map.has(_.email) && JSON.stringify(map.get(_.email)) === JSON.stringify(item)) map.delete(_.email);
return !item
});
console.log(JSON.stringify(newUser));
console.log(JSON.stringify(deleteUser));
console.log([...map.values()]);
[{"id":1,"email":"a@x.y"},{"id":2,"email":"b@x.y"}]
[{"dept_id":2,"email":"d@x.y"},{"dept_id":3,"email":"e@x.y"}]
[{ dept_id: 1, email: 'c@x.y' }]
数组交集
数组拍平
样本。
const sample = [1, 2, [3, 4, 5, [6, 7, 8], 9], 10, [11, 12]];
递归。
function clap(arr){
let cup = [];
arr.forEach(_ => {
if(_ instanceof Array) {
cup = cup.concat(clap(_));
} else {
cup.push(_);
}
});
return cup;
}
console.log(clap(sample));
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
reduce。
function clap(arr){
return arr.reduce((prev, cur)=>{
return prev.concat(Array.isArray(cur) ? clap(cur) : cur);
},[]);
}
console.log(clap(sample));
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
flat。
function clap(arr){
return arr.flat(Infinity);
}
console.log(clap(sample));
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
扩展运算符。有待优化。
function clap(arr){
let cup = [];
let _sign = true;
arr.forEach(_ => {
if(Array.isArray(_)) {
cup.push(..._);
_sign = false;
} else {
cup.push(_);
}
});
if(_sign) return cup;
return clap(cup);
}
console.log(clap(sample));
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
toString。
function clap(arr){
return arr.toString().split(',').map(_ => parseInt(_));
}
console.log(clap(sample));
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
apply。
function clap(arr){
while(arr.some(_ => Array.isArray(_))){
arr = [].concat.apply([],arr);
}
return arr;
}
console.log(clap(sample));
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
清空数组
var arr = [0, 1, 2, 3];
var obj = {val: arr};
arr = [];
console.log(JSON.stringify(obj));
{"val":[0,1,2,3]}
清空数组
var arr = [0, 1, 2, 3];
var obj = {val: arr};
arr.length = 0;
console.log(JSON.stringify(obj));
{"val":[]}
相关问题
今天(2021-1-18)视频面试美团的一个岗位,笔试题是数组去重,如输入 [1, 2, 1, 1, '1'],输出 [1, 2, '1' ],看到题目第一眼我就想起使用 new Set,然后写了如下代码:
...new Set(array)
console.log([...new Set([1, 2, 1, 1, '1'])])
VM254:1 (3) [1, 2, "1"]
接着试探着问面试官应该可以吧,面试官反应平平(我猜测他可能没用过这种方式,也不知道对不对),我也不好再尝试运行,虽然我知道可以解这道题,但是面试官不确定那我还是老老实实写其他代码吧,然后写了如下:
function foo(arr){
var map = {}
var arr2 = []
for(let i=0;i<arr.length;i++){
if(!map[arr[i]]){
map[arr[i]]=arr[i]
}
}
// 遍历 map
for(const key in map){
arr2.push(key)
}
return arr2
}
console.log(foo([1, 2, 1, 1, '1']))
VM271:15 (2) ["1", "2"]
面试官说你看对么,然后我看了一眼发现 Number 1 和 String 1 被等值了,毕竟是 map 是一个 object。我又尝试的问了一下,您觉的这样应该怎么处理呢,面试官说:“你在里面加一下判断,试着把 Number 1 和 String 1 区分开”,我想了一下没什么概念就试探着说其实这里可以用 Map 解决的,只需要把 var map = new Map() 就可以了(我感觉没有我反应快。。。,而且这判断怎么加。。。),面试官无感,我也就没再改代码,然后结束了。事后补全以下代码:
function foo(arr){
var map = new Map()
var arr2 = []
for(let i=0;i<arr.length;i++){
if(!map.get(arr[i])){
map.set(arr[i], arr[i])
}
}
// 遍历 map
for(const [key, value] of map){
arr2.push(key)
}
return arr2
}
console.log(foo([1, 2, 1, 1, '1']))
VM254:1 (3) [1, 2, "1"]
过滤
多层过滤(多维过滤)
数组多层过滤,需要注意引用的问题。
样本数据。
[{
"id": 3541,
"name": "124",
"create_at": "2021-12-26 21:57:41",
"group": "124",
"artboards": [{
"id": 32211,
"name": "one",
"checked": false
}],
"expend": true
}, {
"id": "null",
"group": "未分组",
"artboards": [{
"id": 32131,
"name": "Toast_icon_prompt@2x",
"checked": false
}, {
"id": 32130,
"name": "Toast_icon_prompt@3x",
"checked": false
}],
"name": "未分组"
}]
JSON
JSON.parse(JSON.stringify(foo));
if (''.indexOf(searchValue) > -1) return setCurrentList(groupList);
const groupListTmp = JSON.parse(JSON.stringify(groupList));
const tmpList = groupListTmp.filter(item => {
if (item?.artboards?.length) {
const queryChildrenNode = item?.artboards.filter(item => (item.name.indexOf(searchValue) != -1));
if (queryChildrenNode.length) {
item.artboards = queryChildrenNode;
return 1 === 1;
}
}
// if ((item.name?.indexOf(searchValue) != -1)) return 1 === 1;
});
数组对象
数组取差值
已知两个数组,source 为 输入数组,target 为目标存储的数组,通过原子 key 进行存储的数组的值的插入更新和删除操作。
const source = [
{id: 1, name: 'bob', age: 18},
{id: 5, name: 'lili'},
{id: 8, name: 'lilei', photo: 'htpp://image'}
];
const target = [
{id: 5, name: 'lili'},
{id: 1, name: 'bob', age: 20},
{id: 10, name: 'xiaoming', age: 27, photo: 'htpp://image'}
];
const checkUser = (source, target, key) => {
const map = new Map();
const newUser = source.filter(_ => {
const item = target.find($ => $[key] === _[key]);
if (item && !map.has(_[key])) map.set(_[key], item);
return !item;
});
const deleteUser = target.filter(_ => {
const item = source.find($ => $[key] === _[key]);
if (item && map.has(_[key]) && JSON.stringify(map.get(_[key])) === JSON.stringify(item)) map.delete(_[key]);
return !item;
});
const updateUser = [...map.values()];
return {
add: newUser,
update: updateUser,
delete: deleteUser
};
}
const result = checkUser(source, target, 'id');
console.log(result);
{
add: [ { id: 8, name: 'lilei', photo: 'htpp://image' } ],
update: [ { id: 1, name: 'bob', age: 20 } ],
delete: [ { id: 10, name: 'xiaoming', age: 27, photo: 'htpp://image' } ]
}
一个变体,用来判断是否和如何更新数据库的内容。
const source = [
{mail: 'bob@x.y', name: 'bob', age: 18},
{mail: 'lili@x.y', name: 'lili'},
{mail: 'lilei@x.y', name: 'lilei', photo: 'htpp://image'}
];
const target = [
{id: 5, mail: 'lili@x.y', name: 'lili'},
{id: 1, mail: 'bob@x.y', name: 'bob', age: 20},
{id: 10, mail: 'xiaoming@x.y', name: 'xiaoming', age: 27, photo: 'htpp://image'}
];
const checkUser = (source, target, key, id) => {
const map = new Map();
const newUser = source.filter(_ => {
const item = target.find($ => $[key] === _[key]);
if (item && !map.has(_[key])) map.set(_[key], item);
return !item;
});
const deleteUser = target.filter(_ => {
const item = source.find($ => $[key] === _[key]);
if (item && map.has(_[key])) {
const {[id]: _id, ...data} = map.get(_[key]);
if (JSON.stringify(data) === JSON.stringify(item)) map.delete(_[key]);
else map.set(_[key], {[id]: _id, ...item});
}
return !item;
});
const updateUser = [...map.values()];
return {
add: newUser,
update: updateUser,
delete: deleteUser
};
}
const result = checkUser(source, target, 'mail', 'id');
console.log(result);
{
add: [ { mail: 'lilei@x.y', name: 'lilei', photo: 'htpp://image' } ],
update: [ { id: 1, mail: 'bob@x.y', name: 'bob', age: 18 } ],
delete: [
{
id: 10,
mail: 'xiaoming@x.y',
name: 'xiaoming',
age: 27,
photo: 'htpp://image'
}
]
}
参考
No categories