Vienna Vienna - 1 month ago 5x
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]

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

x = [false, false, false, true, false]

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.


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

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

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


lodash ...

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

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

<script src=""></script>