在javascript对象数组中查找第一个未使用的属性值

Wai*_*ski 0 javascript

寻找一种有效确定最低正整数的方法,该正整数不用作对象数组中任何对象中特定属性的值.

换句话说,我正在寻找一个针对这些数组的函数/算法:

var example1 = [{ id: 1 }, { id: 2 }, { id: 3 }],
    example2 = [{ id: 6 }, { id: 4 }, { id: 2 }],
    example3 = [{ id: 2 }, { id: 1 }, { id: 4, otherProp: 3 }];
Run Code Online (Sandbox Code Playgroud)

将分别返回4,1和3.(显然在本例中使用了id-property.)

我考虑过使用Underscore.js,但是如果没有一些丑陋的嵌套循环,我找不到办法.有没有人有更好的主意?

Ber*_*rgi 5

function next(prop) {
    return function(arr) {
        var used = arr.reduce(function(o, v) {
            o[v[prop]] = true;
            return o;
        }, {});
        for (var i=1; used[i]; i++);
        return i;
    }
}
var nextId = next("id");

nextId([{ id: 1 }, { id: 2 }, { id: 3 }]) // 4
nextId([{ id: 6 }, { id: 4 }, { id: 2 }]) // 1
nextId([{ id: 2 }, { id: 1 }, { id: 4, otherProp: 3 }]) // 3
Run Code Online (Sandbox Code Playgroud)

  • @Pointy:不,他说他想选择要查看的属性(在他的例子中,`id`) (2认同)