1

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.

1
  • Thanks to all of you, I'd accept all your answers which I cannot, so I at least gave you the indirect credit. I accepted the one containing all answers to make it easier for others. Commented May 25, 2020 at 17:18

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

I would rename newArr to final to stay consistent with the question.
1

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)

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.