My Work
My Work

Reputation: 2508

How to change swap (change) 0 to 1 in JavaScript array

Is there some nicer way how to convert 0 to 1 and vice versa in an array in JavaScript than going with for loop and converting it as described here, ie:

var variable1 = [0,1,1,0,0];
var final = []

for (var i=0; i<variable1.length; i++) {
final[i] = 1-variable1[i] 
}
//1,0,0,1,1

Something similar to Python's:

[1-i for i in variable1]
# [1,0,0,1,1]

Thanks.

Upvotes: 1

Views: 932

Answers (3)

octocat512
octocat512

Reputation: 190

var variable1 = [0,1,1,0,0];

var final = variable1.map(v => v ^ 1);

console.log(final);

It is also looping. but I think this code is more readable.

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370659

If you can create a new array, I'd use .map instead:

var variable1 = [0,1,1,0,0];

const final = variable1.map(n => 1 - n);
console.log(final);

Upvotes: 2

Sifat Haque
Sifat Haque

Reputation: 6057

You can use map to shorten the syntex.

final = variable.map(num => 1^num)

var variable = [0,1,1,0,0];
var final1 = variable.map(num => 1-num) // way one
var final2 = variable.map(num => 1^num) // way two
console.log(final1, final2)

Upvotes: 1

Related Questions