JavaScript Find Single element in Array



.NET 的 LINQ 包含一个运算符.Single

返回序列中的唯一元素,

如果序列中没有一个元素,则引发异常。

在最新版本的JavaScript中是否有等效项? (撰写本文时的 ECMA v8(。

我能找到的最接近的操作是.find尽管必须编写自己的样板来断言恰好有一个 elemet 匹配。

.single()的预期功能示例:

const arr = [1, 4, 9];
arr.single(v => v > 8 && v < 10);   // Returns 9
arr.single(v => v < 5);             // Throws an exception since more than one matches
arr.single(v => v > 10);            // Throws an exception since there are zero matches

在最新版本的 JavaScript 中是否有等效项?(撰写本文时的 ECMA v8(。

不,不是。

您可以更改Array的原型(这是不可取的(,并添加一个方法来过滤数组并返回单个找到的项目或引发错误。

Array.prototype.single = function (cb) {
var r = this.filter(cb);
if (!r.length) {
throw 'zero match';
}
if (r.length !== 1) {
throw 'too much matches';
}
return r[0];
};
const arr = [1, 4, 9];
console.log(arr.single(v => v > 8 && v < 10)); // 9
console.log(arr.single(v => v < 5));           // exception since more than one matches
// console.log(arr.single(v => v > 10));       // exception since there are zero matches

或者您可以使用link.js.

const arr = [1, 4, 9];
console.log(Enumerable.From(arr).Single(v => v > 8 && v < 10)); // 9
console.log(Enumerable.From(arr).Single(v => v < 5));           // exception since more than one matches
// console.log(Enumerable.From(arr).Single(v => v > 10));       // exception since there are zero matches
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>

原生 JS 中不存在这样的函数,但是编写自己的函数来完成同样的事情是微不足道的:

const single = (arr, test) => {
let found;
for (let i = 0, l = arr.length; i < l; i++) {
if (test(arr[i])) {
if (found !== undefined) throw new Error('multiple matches found');
found = arr[i];
}
}
if (!found) throw new Error('no matches found');
console.log('found: ' + found);
return found;
}
const arr = [1, 4, 9];
single(arr, v => v > 8 && v < 10);   // Returns 9
single(arr, v => v < 5);             // Throws an exception since more than one matches
single(arr, v => v > 10);            // Throws an exception since there are zero matches

这是假设您实际上没有测试undefined,在这种情况下,您必须编写更多代码

使用 https://www.npmjs.com/package/manipula 可以通过 LINQ 样式执行此操作:

Manipula.from([1, 4, 9]).single(v=> v>8 && v<10)

最新更新