当前位置:网站首页>Array Operations - judgment, de duplication, consolidation, expansion
Array Operations - judgment, de duplication, consolidation, expansion
2022-07-19 01:32:00 【Xu xiaoshuo】
Get the data from the front end and the back end , Or when the front-end data is transferred to the back-end , It is often necessary to operate on arrays , This article summarizes some general operations on arrays .
(1) Determine whether it is an array
When we get a data , When it is still uncertain whether the data is an array , The first thing we need to do is judge the data , Determine whether it is an array . Here are five ways to judge , As shown below :
<script type="text/javascript">
let arr = [1,2,3];
/** The first one is :instanceof */
console.log(arr instanceof Array);
/** The second kind :constructor */
console.log(arr.constructor === Array);
/** The third kind of : Judge whether the object has push Some methods of equal array */
console.log(!!arr.push && !!arr.concat);
/** A fourth :toString */
console.log(Object.prototype.toString.call(arr) === '[object Array]');
/** The fifth :Array.isArray */
console.log(Array.isArray(arr));
</script>The first method :instanceof
instanceof Used to determine whether a variable is an instance of an object . however instanceof There is a problem , Its problem is that it can only conclude that there is only one global execution environment .
The second method :constructor
Through the constructor attribute of the instance constructor Pointing constructor . This method will have the same disadvantages as the first method .
The third method :!!arr.push && !!arr.concat
Judge whether the object contains push Some methods of equal array , This method is simple and easy to use , But there are compatibility issues .
The fourth method :Object.prototype.toString.call()
Object.prototype.toString().call() You can get different types of objects . Its power can not only check whether it is an array , It can also check whether it is a function , Whether it is a number, etc .
The fifth method :Array.isArray()
Array.isArray() Used to determine whether the passed value is an array , Returns a Boolean value . This method is simple and easy to use , Compatibility is good. , You should still consider using this method .
(2) Array weight removal
Array de duplication is also an important operation for arrays . As shown below :
<script type="text/javascript">
// Ordinary box
let arr = [1, 2, 3, 2, 33, 55, 66, 3, 55];
/* The first one is Ergodic de duplication */
let newArr = [];
arr.forEach(item => {
if (!newArr.includes(item)) {
newArr.push(item)
}
})
console.log("newArr: " + newArr);
/* The second kind Skillfully use Set */
let newArr2 = [...new Set(arr)]
console.log("newArr2: " + newArr2);
/* result
newArr:[1, 2, 3, 33, 55, 66]
newArr2:[1, 2, 3, 33, 55, 66]
*/
// Object items
let Oarr = [{
id: 1,
name: 'aa'
},
{
id: 2,
name: 'cc'
},
{
id:3,
name:' The front-end development ',
},
{
id:1,
name:'web front end '
}
]
/* Method 1 */
const mp = new Map(Oarr.map(item => [item['id'],item]))
console.log([...mp.values()])
/* Method 2 */
const unique = (Oarr,key)=>{
return [...new Map(Oarr.map(item=>[item[key],item])).values()]
}
console.log(unique(Oarr,'id'));
/* Output result , The back covers the front
0: {id: 1, name: "web front end "}
1: {id: 2, name: "cc"}
2: {id: 3, name: " The front-end development "}
*/
</script>Here for ordinary arrays and object arrays , Two methods of weight removal are provided , Are simple and practical , Methods with good compatibility , To give you a reference .
(3) Array merge
Here are four commonly used array merging methods , As shown below :
<script type="text/javascript">
let arr1 = ['a', 'b']
let arr2 = ['c', 'd']
let arr3 = ['e', 'f']
/* Method 1 The original array will not change */
let res1 = arr1.concat(arr2);
console.log(res1);
/* Mode two The original array will change */
arr3.push.apply(arr3, arr2);
console.log(arr3);
/* Method 3 */
let res3 = [...arr1,...arr2];
console.log(res3);
/* Method four unshift loop */
for(let i = arr1.length-1;i >= 0;i--) {
arr2.unshift(arr1[i]);
}
console.log(arr2);
</script>In the above method , What we need to pay attention to , Does the merge provided by this method change the original array , Choose the appropriate consolidation method according to specific needs .
(4) Array expansion
Before we de duplicate the array 、 After merging , Of course, it is also necessary to expand the array , Here are five methods of array expansion , As shown below :
<script type="text/javascript">
let arr = [1,2,[3,4],[5,6,[7,8,9]]]
/* Mode one flat */
let res1 = arr.flat(Infinity);
console.log(res1);
/* Mode two join+split */
let res2 = arr.join().split(',').map(Number);
console.log(res2)
/* Mode three toString+split */
let res3 = arr.toString().split(',').map(Number);
console.log(res3);
/* Mode 4 Recursive expansion */
const flattern = arr =>{
const res = []
arr.forEach((item)=>{
if(Array.isArray(item)){
res.push(...flattern(item));
}else{
res.push(item)
}
})
return res
}
console.log(flattern(arr));
/* Methods five recursive concat */
function flattern2(arr){
return [].concat(
...arr.map(item=>Array.isArray(item)?flattern2(item):item)
)
}
console.log(flattern2(arr));
</script>Above is the expansion of a multidimensional nested array , These five methods are only for your reference .
The above is the content of this article , Of course, there are many operations on arrays , For example, delete 、 Sort 、 Interception and so on , There is no introduction here , We will mention again in the following article , If there is anything wrong with this article , Please leave a message , thank you ~
边栏推荐
- uni canvas截取图片
- C Programming Language(2nd Edition)--读书笔记--1.5
- JS intercepts the first few digits of the string or the last few digits of the string
- 使用leaflet仿原神提瓦特大地图制作日记
- Add, delete, modify and check the connection between the two tables
- 解决小程序自定义底部菜单切换闪动
- [GFCTF 2021]Baby_ Cve-2021-41773 on the web
- three.js初体验:模拟一个小树杈的生长
- Vue project deployment, cleaning cache
- uni-app微信小程序——商城(7)——商品详情
猜你喜欢

PCRE bypasses regular

当 std::bind 遇上 this

gtest与gmock的安装与使用
![Eye of depth III - (7)] mathematics: application of SVD decomposition](/img/18/f69d012ebadf2c7aedfbea40ae1cf5.png)
Eye of depth III - (7)] mathematics: application of SVD decomposition

Uni app wechat applet - Mall (4) - merchants

object-fit:cover; It doesn't work in the applet. How to deal with the deformation of the applet image
![[elementui El date picker date selector, the end time must not be earlier than the start time, and only the date of the specified number of days from the start time can be selected]](/img/73/af7ca3f670ffee18081b9ca6a9ccf6.png)
[elementui El date picker date selector, the end time must not be earlier than the start time, and only the date of the specified number of days from the start time can be selected]

Assemblage stylisé de cartes de commutation auto - encapsulées

Uni app wechat applet - Mall (6) - my home page

uni-app微信小程序——商城(7)——商品详情
随机推荐
小程序swiper高度
Day12 Association serialization processing
今天的码农女孩总结了jQuery处理缓存的方法和事件委托方法的区别的笔记
小程序嵌入网页向小程序跳转并传参,微信小程序中实现公众号授权获取openId
Maker-鸿蒙应用开发培训笔记03
Use bat to automatically execute CMD commands (multiple commands or a single command)
Redis简单使用
uni canvas截取图片
gtest与gmock的安装与使用
Page layout - three column layout solution
Win10 vscode 代码格式化设置与远程断点调试
js获取一个文件名的后缀格式
“我的”Bug大全(转载)
[SWPU 2019] network TTL encryption and some related knowledge
服务器如何安装宝塔面板?(宝塔面板安装教程)
鼠标右键菜单添加快速打开选项遇见的错误:
CTF CRYPTO RSA入门刷题
[GFCTF 2021]Baby_ Cve-2021-41773 on the web
Common mode attack and shared prime of RSA
单页面应用 SPA 和多页面应用 MPA