1

If I have this pice of code which checks is something already exist inside array

var array = [ 1, 5, 12, 31, 7, 69 ];

var array = $.grep(array, function(n, i) {
  return (n == 112);
});

alert(array.length);

my question is simple one: How can I pass variable to this grep function and to use it instead of hardcoded 112 value inside expression?

user1765862
  • 13,635
  • 28
  • 115
  • 220

6 Answers6

5

You can just pass a variable from the outside. JavaScript's lexical scope allows for variables from the outside scope to be passed into deeper functions.

http://jsfiddle.net/ag1djcjm/

var array = [ 1, 5, 12, 31, 7, 69];
var code = 112;

// No need to declare variables twice
array = $.grep(array, function(n, i) {
  return (n == code);
});

alert(array.length);
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
z1m.in
  • 1,661
  • 13
  • 19
  • 1
    This answer doesn't mention `array` being declared _twice_. – Cerbrus Nov 25 '15 at 08:34
  • @Cerbrus, what is wrong here? OP not say that want save previous state – Grundy Nov 25 '15 at 08:35
  • @Cerbrus, possibly i not quite understand it, can you a bit explain? – Grundy Nov 25 '15 at 08:36
  • 1
    `var array` is in there twice. That's bad. – Cerbrus Nov 25 '15 at 08:38
  • 2
    @Cerbrus, but in this case not matter. Just not saved previous state, so OP have just filter result – Grundy Nov 25 '15 at 08:38
  • 1
    Because it can result in unexpected behaviour. In this specific case it may not be a problem, but getting used to coding this way will eventually result in problems. Imo, answers should fix _all_ problems in the OP's code (as far as reasonable) – Cerbrus Nov 25 '15 at 09:03
3

Try like this

var array = [ 1, 5, 12, 31, 7, 69 ];

var val=112;
// remove var from here it'll re-declare same variable
array = $.grep(array, function(n, i) {
  return (n == val);
});

alert(array.length);

JSFIDDLE

You can do it by javascript's .filter() also

Like this

var array = [ 1, 5, 12, 31, 7, 69 ];
var val=112;
array = array.filter(function(n) { return n == val; });
alert(array.length);

JSFIDDLE

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
  • This answer doesn't mention `array` being declared _twice_. – Cerbrus Nov 25 '15 at 08:34
  • @Cerbrus does it arise any error or op faced any problem for this ? – Anik Islam Abhi Nov 25 '15 at 08:36
  • 3
    Code doesn't have to throw an error to be _wrong_. Declaring a variable _twice_ is wrong. – Cerbrus Nov 25 '15 at 08:37
  • @Grundy While it doesn't have issues with `var`, this code will have issues when trying to do the same with `let` or `const`, which is where JavaScript is currently going towards. Also, in just about any other programming language, declaring a variable twice will result in an error. – Madara's Ghost Nov 25 '15 at 08:59
  • 1
    @Grundy Redeclaring a variable goes against conventions and misrepresents the variable as newly declared, which may mislead subsequence coder into writing buggy code. Unlike most conventions, there is really no reason to do it, so it is traditionally wrong. It is tolerated on a technical level only because of backward compatibility. – Sheepy Nov 25 '15 at 08:59
  • @MadaraUchiha, but now used _var_ and not _let_ or _const_ :-) – Grundy Nov 25 '15 at 09:00
  • 1
    @Grundy Using global variables is not technically wrong either. Doing this: `(function() { (function() { (function() { (function() { alert('foo'); })(); })(); })(); })(); })();` is not technically wrong either. Doesn't mean they're any good. – Madara's Ghost Nov 25 '15 at 09:02
2

Just define the value you need to filter before calling $.grep function. See example below

var array = [1, 5, 12, 31, 7, 69],
    filterValue = 5;

var newArray = $.grep(array, function (n, i) {
    return n == filterValue;
});

Since you're redefining the array, I created a new variable newArray and assigned filtered values to that, but you can still assign it to array variable.

Nipuna
  • 6,846
  • 9
  • 64
  • 87
2

Code:

function filter ( data, val ) {
    return $.grep(data, function ( n, i ) {
        return (n == val);
    });
}

Test:

var array = [ 1, 5, 12, 31, 7, 69];
var test = filter(array, 112);
alert(test.length);
Andy W
  • 594
  • 2
  • 12
2

So, what you're basically trying to do, it determine if an array of numbers contains a certain number (variable).

There's no need to over-complicate this with grep. Just use indexOf:

var array = [ 1, 5, 12, 31, 7, 69 ],
    search = 112,
    hasNumber = array.indexOf(search) !== -1;

// Using this so that it's visible in the snippet.
document.body.textContent = hasNumber;
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • 1
    @Cerbus Yes, though this is not Question ? Could use `Array.prototype.filter()` in place of `$.grep()` to avoid calling `jQuery` as well – guest271314 Nov 25 '15 at 09:15
  • 2
    I've removed all of the bridge comments, let's not discuss the viability of papers for bridge building. An answer providing an alternative solution to a problem is viable, even if it doesn't exactly use OP's way. OP may be using `$.grep()` because they aren't aware of solutions like `indexOf()` and `filter()`. Answers bringing extra ways to OP's attention are valid. – Madara's Ghost Nov 25 '15 at 09:27
1

Could create a function outside of $.grep() , to be called for each item in array ; could also pass additional parameters to function . Also try defining different variable names for input array , resulting array

var array = [ 1, 5, 12, 31, 7, 69 ], num = 112
, compare = function(n, i) { return n === num }

var res = $.grep(array, compare);
guest271314
  • 1
  • 15
  • 104
  • 177
  • 1
    you have a typo, or answer wrong: variable _num_ but parameter name - _n_ in both functions. So here IIFE you can delete and nothing changed – Grundy Nov 25 '15 at 08:42
  • Yep, now seems OK :-) But i not quite understand why here need IIFE? can you a bit explain? :-) – Grundy Nov 25 '15 at 08:47
  • @Grundy _"not quite understand why here need IIFE?"_ Not "need" for an IIFE ; only a possible option for "How can I pass variable to this grep function and to use it instead of hardcoded 112 value inside expression?" . Could potentially be achieved using several different approaches ? – guest271314 Nov 25 '15 at 09:03
  • 1
    @guest271314 This seems a bit more excessive than just passing a variable from the outside scope. Less readable and less performant too. (Still a valid answer, of course). – Madara's Ghost Nov 25 '15 at 09:04