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

标签 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 }];

将分别返回 4、1 和 3。 (在本例中显然使用了 id 属性。)

我考虑过使用 Underscore.js 来实现这一点,但我找不到一种没有一些丑陋的嵌套循环的方法。有人有更好的主意吗?

最佳答案

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

关于javascript - 查找 javascript 对象数组中第一个未使用的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22715198/

相关文章:

javascript - 如何使用 node.js 和 redis Laravel 5 监听事件

javascript - Cordova iOS 在应用程序关闭时丢失存储空间

javascript - react : can't access passed props (but CAN access props from router)

javascript - 如何使用 array_merge 在 PHP/Highcharts 中显示非引用命令?

javascript - 在 JavaScript 中,如何使用 [] 运算符访问从 Array 继承的对象?

javascript - POST 方法未发送所有数据

javascript - Ractive.js 事件代理中 jQuery 的 $(this) 的等价物

javascript - Angular Select 不改变模型属性

javascript - 如何基于 ViewPort 重定向我的 Ember 应用程序

javascript - AES 解密在 forge 中失败,但在 crypto-js 中有效