开发者

Extracting the most duplicate value from an array in JavaScript?

my question is actually similar to: Extracting the most duplicate value from an array in JavaScript (with jQuery)

Solution (the one I found as the best, and slightly changed by me):

v开发者_如何学Goar arr     = [3, 7, 7, 7, 7, 10, 10, 8, 5, 5, 5, 5, 20, 20, 1],
result  = {}, 
max     = 0, 
res;

for( var i = 0, total = arr.length; i < total; ++i ) {
var val = arr[i],
    inc = ( result[val] || 0 ) + 1;

result[val] = inc;

if( inc > max ) { 
    max = inc;
    res = val;
}
}
alert(res);

I would like to add an extra which is : if we have, say two numbers with the same number of occurrences, how could we find the minimum of them (the above should alert 5 and not 7, which is the case)? The current solution works for getting only the first most duplicate found, but it does not deal with repetition. Thanks!


Sort the array before you count the incidences:

var arr = [3, 7, 7, 7, 7, 10, 10, 8, 5, 5, 5, 5, 20, 20, 1];

function min_most_duplicate (arr) {
    var result = {},
        max = 0,
        res;

    arr = arr.slice(0); // make a copy of the array
    arr.sort(function(a, b) { return (a - b); }); // sort it numerically

    for( var i = 0, total = arr.length; i < total; ++i ) {
        var val = arr[i],
        inc = ( result[val] || 0 ) + 1;

        result[val] = inc;

        if( inc > max ) { 
            max = inc;
            res = val;
        }
    }

    return res;
}

min_most_duplicate(arr); // returns 5

This works because the way the for loop is written it's going to return the first one that it finds that has the most duplicates, so if the array is sorted, the smallest number will come first, so it'll be the one that the for loop finds.


This would work, example:

var arr = [3, 7, 7, 7, 7, 10, 10, 8, 5, 5, 5, 5, 20, 20, 1],
    result = {},
    max = 0,
    res, key, min;

for (var i = 0, total = arr.length; i < total; ++i) {
    var val = arr[i],
        inc = (result[val] || 0) + 1;

    result[val] = inc;

    if (inc > max) {
        max = inc;
        res = val;
    }
}
for (var i in result) {
    if (result[i] === max) {
        key = parseInt(i, 10);
        min = min || key;
        console.log(min)
        if (min > key) {
            min = key;

        }
    }
}
res = min;
alert(res);


let getMostDuplicated = array => {
    let duplicated = '';
    let max        = 0;
    for (let i = 0; i < array.length; i++) {
        let counter = 0;
        for (let j = 1; j < array.length - 1; j++) {
            if (array[i] === array[j])
                counter++;
        }

        if (counter > max) {
            duplicated = array[i];
            max        = counter;
        }

    }

    return duplicated;
};

let array = [3, 7, 7, 7, 7, 10, 10, 8, 5, 5, 5, 5, 20, 20, 1];
getMostDuplicated(array);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜