Home > Article > Web Front-end > Application of arrays in js and introduction to four methods of array deduplication (code)
What this article brings to you is about the application of arrays in js and the introduction (code) of four methods of array deduplication. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Input n, and output n rows of symmetrical arrays to form a pyramid:
function output(n) { for(let i=0;i<=n;i++){ let k=0; var a=[]; for(let j=1;j<=2*i-1;j++){ if(j<=i){ a.push(++k); }else{ a.push(--k); } } console.log(a) } }
2. Array deduplication
Method 1: Traverse the array method
// 最简单数组去重法 function unique1(array){ var n = []; //一个新的临时数组 //遍历当前数组 for(var i = 0; i < array.length; i++){ //如果当前数组的第i已经保存进了临时数组,那么跳过, //否则把当前项push到临时数组里面 if (n.indexOf(array[i]) == -1) n.push(array[i]); } return n; }
Method Two: Array Subscript Judgment Method
function unique3(array){ var n = [array[0]]; //结果数组 //从第二项开始遍历 for(var i = 1; i < array.length; i++) { //如果当前数组的第i项在当前数组中第一次出现的位置不是i, //那么表示第i项是重复的,忽略掉。否则存入结果数组 if (array.indexOf(array[i]) == i) n.push(array[i]); } return n; }
Method Three: Optimizing Traversing Array Method
// 思路:获取没重复的最右一值放入新数组 function unique5(array){ var r = []; for(var i = 0, l = array.length; i < l; i++) { for(var j = i + 1; j < l; j++) if (array[i] === array[j]) j = ++i; r.push(array[i]); } return r; }
Method Four: Traversing Array
function unique(array){ var a=[]; for(var i=0;i<array.length;i++){ var flag=0; for(var j=0;j<a.length;j++){ if(array[i] == a[j]) var flag=1; } if(flag==0){ a.push(array[i]); } } return a; }
Related Recommendations :
Detailed analysis of variable declaration and function declaration promotion in js (with examples)
Summary of asynchronous loading methods for js files (with code)
The above is the detailed content of Application of arrays in js and introduction to four methods of array deduplication (code). For more information, please follow other related articles on the PHP Chinese website!