Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Find Single element in Array

.NET's LINQ contains an operator .Single which

Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.

Is there an equivalent in the latest version of JavaScript? (ECMA v8 at time of writing).

The closest operation that I could find was .find though one would have to write their own boilerplate to assert that exactly one elemet matched.

Example of expected functionality of .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
like image 448
Jacob Horbulyk Avatar asked Feb 04 '26 17:02

Jacob Horbulyk


1 Answers

Is there an equivalent in the latest version of JavaScript? (ECMA v8 at time of writing).

No, it is not.

You could change the prototype of Array (which is not advisable) and add a method which filters the array and returns a single found item or throws an error.

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

Or you could use 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>
like image 159
Nina Scholz Avatar answered Feb 07 '26 05:02

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!