开发者

Is there a way to sort duplicates into a group that are found in an array using jquery or javascript

I have an array such as:

var aos = ["a","a","b","c","d"];

and I want to know if I can find duplicates of each index and store them into something such as an arraylist? For instance we start at:

aos[0]

That then checks to see if

a

is found, and it will keep running through the array taking all the elements with that value in ind开发者_C百科ex 0 storing them into a list (such as an arraylist or collection) and then removing them from the list. Is this possible?


var uniq =_.uniq(aos)

Or a long winded way (ES5) :

var uniq = aos.reduce(aos, function(memo, val) {
    if (!aos.some(function(elem) { return elem === val; })) {
         return memo.push(val);
    }
}, []);

And if you want to support ES3 then :

var uniq = [];
for (var i = 0, ii = aos.length; i < ii; i++) {
    var contains = false;
    for (var j = 0, jj < uniq.length; j < jj; j++) {
        if (uniq[j] === aos[i]) {
            contains = true;
            break;
        }
    }
    if (!contains) {
        uniq.push(aos[i]);
    }
}

Store duplicates in a new array:

var duplicates = _.select(aos, function(val) {
    var true = _.after(2, function() { return true; });
    return _.any(aos, function(elem) {
        return elem === val ? true() : false;    
    });
});

Live Example

_.uniq, Array.prototype.reduce, Array.prototype.some, _.any, _.select, _.after


Basically you want to remove duplicate items?, try this:

function unique_array(array) {
    var result = []
    for (var i = 0; i < array.length; ++i) {
        for (var j = i + 1; j < array.length; ++j) {
            if (array[i] === array[j]) {
                j = ++i;
            }
        }
        result.push(array[i]);
    }
    return result;
}

Or

Array.prototype.unique = function() {
    var result = []
    for (var i = 0; i < this.length; ++i) {
        for (var j = i + 1; j < this.length; ++j) {
            if (this[i] === this[j]) {
                j = ++i;
            }   
        }
        result.push(this[i]);
    }
    return result;
}

Array.prototype.duplicates = function() {
    var result = []
    for (var i = 0; i < this.length; ++i) {
        for (var j = i + 1; j < this.length; ++j) {
            if (this[i] === this[j]) {
                result.push(this[i]);
                j = ++i;
            }           
        }
    }
    return result;
}

// aos.unique() => a,b,c,d
// aos.duplicates() => a
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜