0

Coming from a matlab background, I am trying to replicate the following scenario in Javascript

A = [1, 2, 3, 4, 5];
B = 4;
C = A == B;
answer => C = [0, 0, 0, 1, 0]

In other words, it generates a logical array where only the value compared is set to 1. I can do this using a loop but I was wondering if there a 1 liner solution to this in javascript?

1
  • 2
    No there is not. JavaScript is not that kind of programming language. There's the .filter() function on the Array prototype however. (Well .map(); not enough coffee yet :) Commented Dec 17, 2013 at 14:40

4 Answers 4

4

You can use the map() function to do something similar to what you were looking for:

var A = [1, 2, 3, 4, 5];
var B = 4;
var C = function (x) { return +(x === B); };
var answer = A.map(C);

var C = x => +(x === B); would look cleaner, but that's ES6 code (experimental).

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

Comments

2

About the fanciest you could get would be

var C = A.map(function(v) { return v == B ? 1 : 0; });

That's supported in newer JavaScript runtime systems.

In JavaScript it'd probably be more idiomatic to prefer a result array containing boolean values:

var C = A.map(function(v) { return v == B; });

Comments

2

There's not a one-liner, but using Array.map can get you pretty close to what you want:

 var a = [1, 2, 3, 4, 5];
 var b = 4;
 var c = a.map(function(item) { return item === b? 1: 0; });

 console.log(c);

Fiddle

Note map isn't supported by older browsers, the MDN link above has polyfil code or you can include any number of libraries that provide something equivalent (e.g. jQuery has a .map() function).

1 Comment

Thanks for pointing out the it is only supported in newer browsers
1

You could write your own function :

function equals(a, b) {
    var result = [];
    while (result.length < a.length) {
        result.push(+(a[result.length] == b));
    }
    return result;
}

var A = [1, 2, 3, 4, 5];
var B = 4;
var C = equals(A, B); // [0, 0, 0, 1, 0]

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.