开发者

How to select unknown numbers in javascript?

开发者 https://www.devze.com 2023-01-17 22:02 出处:网络
So for example I have: array(2,1,3,4,5,6,7) and I already know (2,1,3) How should I get (4,5,6, 7) if I know that all numbers exists from 1 to 7 and the numbers what I 开发者_如何转开发already know

So for example I have:

array(2,1,3,4,5,6,7)

and I already know (2,1,3)

How should I get (4,5,6, 7) if I know that all numbers exists from 1 to 7 and the numbers what I 开发者_如何转开发already know

So I want an array with the numbers what I don't know yet.

Sorry if sounds stupid :|


If A = (2, 1, 3) and B = (1, 2, 3, 4, 5, 6, 7)

Then do you want the uncommon elements (i.e., elements not existing in either)? You can try this:

//note: could be improved - wrote it quickly
function uncommon(a, b) {

    var map = {};
    var alreadyAdded = {};
    var uncommonElements = [];

    var arrays = (a.length > b.length) ? 
                     {first: b, second: a} : 
                     {first: a, second: b};

    for(var i = 0; i < arrays.first.length; i++) {
        map[arrays.first[i]] = true;
    }

    for(var i = 0; i < arrays.second.length; i++) {
        if(!map[arrays.second[i]]) {
            uncommonElements.push(arrays.second[i]);
            alreadyAdded[arrays.second[i]] = true;
        }
    }

    for(var i = 0; i < arrays.first.length; i++) {
        if(!map[arrays.second[i]] && !alreadyAdded[arrays.first[i]]) {
            uncommonElements.push(arrays.first[i]);
        }
    }

    return uncommonElements;
}

Also note that if you had:

A = (2, 1, 3, 9) and B = (1, 2, 3, 4, 5, 6, 7), you would get (2, 1, 3, 9) i.e., elements not found in either one.

0

精彩评论

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