简体   繁体   English

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

[英]Find the first unused property value in an array of javascript objects

In looking for a way to efficiently determine the lowest positive integer that is not used as a value of a specific property in any object within an array of objects.在寻找一种方法来有效地确定在对象数组中的任何对象中未被用作特定属性值的最小正整数。

In other words, I'm looking for a function/algorithm that for these arrays:换句话说,我正在寻找适用于这些数组的函数/算法:

var example1 = [{ id: 1 }, { id: 2 }, { id: 3 }],
    example2 = [{ id: 6 }, { id: 4 }, { id: 2 }],
    example3 = [{ id: 2 }, { id: 1 }, { id: 4, otherProp: 3 }];

Would return 4, 1 and 3 respectively.将分别返回 4、1 和 3。 (Obviously using the id-property, in this example.) (在本例中显然使用了 id 属性。)

I considered using Underscore.js for this, but I couldn't find a way to do it without some ugly nested loops.我曾考虑为此使用 Underscore.js,但如果没有一些丑陋的嵌套循环,我无法找到一种方法。 Does anybody have a better idea?有人有更好的主意吗?

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

One possible approach:一种可能的方法:

function aiKey(arr, prop) {
  var indices = [];
  arr.forEach(function(el) {
    indices[ el[prop] ] = true;
  });
  for (var i = 1, l = indices.length; i < l; i++) {
    if (indices[i] === undefined) {
      break;
    }
  }
  return i; 
}

aiKey(example1, 'id'); // 4
aiKey(example2, 'id'); // 1
aiKey(example3, 'id'); // 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM