Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数组去重方法 #16

Open
hello-tsai opened this issue Sep 19, 2019 · 6 comments
Open

数组去重方法 #16

hello-tsai opened this issue Sep 19, 2019 · 6 comments

Comments

@hello-tsai
Copy link
Owner

hello-tsai commented Sep 19, 2019

一 es6
方法一
var removeDuplicates = function(nums) { return Array.from(new Set(nums)) };
方法二

var removeDuplicates = function(nums) {
    return [...(new Set(nums))]
};
@hello-tsai
Copy link
Owner Author

hello-tsai commented Sep 20, 2019

二 双重循环+splice

function a(nums){
    for (var i=0 ;i<nums.length;i++){
        for (var j=i+1 ; j<nums.length;j++){
            if(nums[i] === nums[j]){
                nums.splice(j,1)
                j--
            }

        }
    }
    return nums
}

@hello-tsai
Copy link
Owner Author

hello-tsai commented Sep 20, 2019

单层循环+splice

function a(nums){
    let cur =  nums[0]
    for (var i=1 ;i<nums.length;){
       if (nums[i] === cur){
           nums.splice(i,1)

       }else{
           cur = nums[i++]
       }
    }
    return nums
}

@hello-tsai
Copy link
Owner Author

hello-tsai commented Sep 20, 2019

四、单层循环+indexof去重

function a(nums){
    let nums2 =[]
    for(let i=0;i<nums.length;i++){
        if (nums2.indexOf(nums[i]) === -1){
            nums2.push(nums[i])
        }
    }
    return nums2
}

@hello-tsai
Copy link
Owner Author

五、利用排序

function a(nums){
    let nums2 = nums.sort()
    for(let i=1;i<nums.length;i++){
        if(nums2[i] === nums2[i-1]){
            nums2.splice(i-1,1)
            i--
        }
    }
    return nums2
}

nums=[1,1,1,2,2,2,3,3,3,4]
console.log(a(nums));

@hello-tsai
Copy link
Owner Author

六、includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

function a(nums){
    let  nums2 =[]
   for(let i=0;i<nums.length;i++){
       if(nums2.includes(nums[i]) === false){
           nums2.push(nums[i])
       }
   }
   return nums2
}

@hello-tsai
Copy link
Owner Author

七、利用hasOwnProperty方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性(也就是,是否有指定的键)。
function a(nums) {
let nums2 = {};
for(let i=0;i<nums.length;i++){
if (nums2.hasOwnProperty(nums[i]) === false)
nums2[nums[i]] = true
}
console.log(nums2);
return Object.keys(nums2)
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant