Vienna Vienna - 3 months ago 9
Javascript Question

Array Functions: Set a certain index true and all others in the array should be set false

Assumed I've an array like:

x = [true, false, false, false, false]
--0-----1------2------3------4----


and I want to set x[3] true and all other must be set to false:

x = [false, false, false, true, false]
---0-----1------2------3------4----


like a radio button group.

Do you know a library (lodash, underscore,..) which has such of function?

EDIT: Thank you very much with the answers. I need a library because the real structure is much more complicated and it should work also in old libraries. The NativeJS examples with map are not cross-browser-able.

Answer

You could use Array#map and check the index if it match.

var x = [false, false, false, false, false],
    n = 3;

x= x.map(function (_, i) { return n === i; });

console.log(x);

lodash ...

var x = [false, false, false, false, false],
    n = 3;

x= _.map(x, (_, i) => n === i);

console.log(x);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Comments