0

Say you have a simple array with random numbers, given the following code, how would i reduce the line of code to use a ternary operator to render the following.

[1, 2, 1, 4, 6]

let arr = [1, 2, 3, 4, 6, 8, 9, 12, 13, 15];

let myArray = arr.map((val, i, arr) => {
  if (val % 2 === 0) {
    return val
  } else {
    return val % 2
  }
});

console.log(myArray)

2
  • 1
    Oops, not a dupe, you're using return val % 2, not val * 2 (though it's exactly the same in all other respects) Commented Apr 4, 2019 at 7:59
  • so many good answers, but i can only pick one. :( Commented Apr 4, 2019 at 8:10

3 Answers 3

3

Logical OR can do the trick for you.

let arr = [1,2,3,4,6,8,9,12,13,15]

let myArray = arr.map((val) => val % 2 || val);

console.log(myArray)

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

Comments

2

You could take a bitwise AND & or (with logical OR ||) the value, instead of a conditional (ternary) operator ?:.

Bitwise AND with a value of one returns either one or zero, depending on the other operand.

var array = [1, 2, 3, 4, 6, 8, 9, 12, 13, 15],
    result = array.map(v => v & 1 || v);

console.log(result);

Comments

1

Just write the ternary condition as a single liner:

const arr = [1,2,3,4,6,8,9,12,13,15];

const myArray = arr.map((val) => val % 2 === 0 ? val: val % 2);

console.log(myArray);

3 Comments

Good answer. Just imho : You can use const instead of let as you are not reassigning the arr nor the myArray . Also why add i and arr in the map if you are not using them ? also arr is used before so you shouldn't use 'shadow' naming.
I like this answer the most
@randal glad to help

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.