7.数组去重

Javascript中去除重复的方式

利用filter,indexof,lastIndexOf对基本类型数组去重

var noFruits, fruits = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry'];

function RemoveRepeat() {
    noFruits = fruits.filter(function (value, index, array) {
        //return array.indexOf(value) === index;
        return array.indexOf(value) === array.lastIndexOf(value);
    })
}

利用lastIndexOf,splice对基本类型数组去重

var nums = [4,5,4,6,7,8]
function RemoveRepeat() {
    for (var i = 0; i < nums.length; i++) {
        if (i !== nums.lastIndexOf(nums[i])) nums.splice(i, 1);
    }
}

对象数组去重

var Messages = [
    {
        "timestamp": 1474328370007,
        "message": "hello"
    },
    {
        "timestamp": 1474328302520,
        "message": "how are you"
    },
    {
        "timestamp": 1474328370007,
        "message": "hello"
    },
    {
        "timestamp": 1474328370007,
        "message": "hello"
    }
]

var NoRepeatMessages = [];

function RemoveRepeat() {
    var hashFlag = {};
    Messages.forEach(function (value, index, array) {
        if (!hashFlag[value.timestamp]) {
            hashFlag[value.timestamp] = true;
            NoRepeatMessages.push(value);
        }
    });
}
JSRUN notes