3

I have a javascript array like:

var arr = ['black', 'white'];

Now if I have a variable containing one of the element, how can I easily get the other? For example

var color = 'black';
var otherColor = '???'; // should be 'white', how can I get it?

I'm looking for the simplest/cleaner way possible.

Also, I don't want to mutate the original array.

Thanks

ANSWER

What about:

var otherColor = arr[1 - arr.indexOf(color)]
1
  • A precaution - all the solutions given below are assuming that your array will never increase/decrease in size (2 item of length). Commented Apr 7, 2016 at 20:39

5 Answers 5

3

You can use Array.prototype.filter for that:

var arr = ['black', 'white'];
var color = 'black';
var otherColor = arr.filter(function(item){ return item !== color })[0];
Sign up to request clarification or add additional context in comments.

Comments

2

Ternary if statement:

var otherColor = arr[0] === color ? arr[1] : arr[0];

Comments

1

arr.filter(x => x !== color)[0]

Comments

0

Here's an ES6 solution using destructuring to throw into the mix.

const arr = ['black', 'white']; // our list of values.
const [black, white] = arr; // destructured into variables black and white
const color = 'black'; 
cont otherColor === black ? black : white;

1 Comment

This solution also uses a ternary. I added this for an extra solution though. It's not the simplest and by your sample you're not using ES6 anyway.
0
var otherColor = arr[1 - arr.indexOf(color)]

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.