1. 程式人生 > >Js 數組操作集合

Js 數組操作集合

max {} 多維數組 維數 sar lte temp isa 尋找

推薦空閑時親手練習一下 必定有所裨益

以下都是鄙人親手練習總結

去重

let a=["1",1,2,3,5,4,2,4,1,6];

[...(new Set(a))]; //["1", 1, 2, 3, 5, 4, 6]

Array.from(new Set(a));  //["1", 1, 2, 3, 5, 4, 6]

function unique(arr){
    let temp={},result=[];
    arr.concat().forEach(item=>{
        if(!temp[typeof(item)+item]){
            result.push(item);
            temp[
typeof(item)+item]=1; } }) return result } unique(a); //["1", 1, 2, 3, 5, 4, 6]

尋找重復次數最多或最少的元素

let a=[1,2,3,2,4,5];

console.log(max(a)); //2
console.log(min(a)); //1

function max(arr) {
    let temp = {},max=arr[0];

    for (let i=0,l=arr.length;i<l;i++) {
        if (!temp[arr[i]]) {
            temp[arr[i]] 
= 1; } else { temp[arr[i]]++; } } for(let x in temp){ max=temp[x]>temp[max]?x:max; } return max } function min(arr) { let temp = {},min=arr[0]; for (let i=0,l=arr.length;i<l;i++) { if (!temp[arr[i]]) { temp[arr[i]]
= 1; } else { temp[arr[i]]++; } } for(let x in temp){ min=temp[x]<temp[min]?x:min; } return min }

尋找不第一個未重復的元素

let a=[1,2,3,4,3,2,1,5];

function get(arr){
    let result=[],temp=arr.concat();
    temp.forEach(item=>{
        if(temp.indexOf(item)===temp.lastIndexOf(item)) result.push(item);
    });
    return result[0];
}

get(a); //4

尋找兩數組最小的相同元素

let a=[1,5,2,3],b=[3,2,4,1];

function get(arr1,arr2){
        let a1= arr1.concat().sort((a,b)=>{return a-b}),
             a2 = arr2.concat().sort((a,b)=>{return a-b}),
         s=new Set(a2);
    return a1.filter(item=>{
        return s.has(item);
    }).sort((a,b)=>{return a-b})[0];
}

get(a,b); //1

展開多維數組

let arr = [1,2,[3],4,[5,[6]]];

function get(arr) {
    for (let i in arr) {
        if (Array.isArray(arr[i])) {
            arr.splice(i, 1, ...get(arr[i]));
        }
    }
    return arr
}

get(arr);  //[1,2,3,4,5,6]

差集、交集

let a=[1,2,3,5],b=[1,2,5],s=new Set(b);

//差集
a.filter(item=>{return !s.has(item)}); 
//[3]

//交集
a.filter(item=>{return s.has(item)}); 
//[1,2,5]

Js 數組操作集合