In C#, I could check if any of the nested List
collection has a value. Example of such structure Check a List[]> contains a value using Linq
List<int> a= new List<int>(){ 2, 2, 3, 4, 5};
List<int> b= new List<int>() { 2, 2, 2, 6 };
List<List<int>[]> c = new List<List<int>[]>();
c.Add(new[]{a,b});
// checking if the value is in any of the collections. for example, this will result to 2
var result = c.SelectMany(x => x).SelectMany(x => x).Any(p => p == 2);
but since I'm exploring the LINQ capabilities in node js , I decided to extend this to an Array of Arrays
var data= [[2, 2, 3, 4, 5],[2, 2, 2, 6], [9], [13, 1,1,90]];
var LINQ = require('node-linq').LINQ;
var resultI=new LINQ(data).Any(function(row)
{
return checkElement(row);
});
console.log(resultI);
function checkElement(array)
{
for(var i = 0 ; i< array.length; i++)
{
if(array[i]== 19){
return true;
}
}
}
Note: I installed the LINQ module using
npm install https://github.com/wearefractal/node-linq/tarball/master
Can this be improved? please any suggestions will be quite appreciated.
2 Answers 2
Style
Your braces are not styled consistently, and most JavaScript developers find sameline braces more idiomatic.
I think it is better form to place your
requires
all the way on the top
Approach
You basically rewrote
Array.indexOf
, except that indexOf gives more info (where is the element), so I would rewrite this with indexOf.Searching for value 19 makes your hasElement function very limited, it would be a more flexible function if you pass the row and the search value.
All in all, I would counter-propose something like this:
var LINQ = require('node-linq').LINQ;
var data= [[2, 2, 3, 4, 5],[2, 2, 2, 6], [9], [13, 1,1,90]];
var resultI=new LINQ(data).Any(function(row){
return hasElement(row, 19);
});
console.log(resultI);
function hasElement(array, value){
return array.indexOf( value ) != -1;
}
The next level?
The flow of LINQ gets a bit broken with the inline function, it would be even cooler if you would call a function there that returns a function seeking for the right value:
var LINQ = require('node-linq').LINQ;
var data= [[2, 2, 3, 4, 5],[2, 2, 2, 6], [9], [13, 1,1,90]];
var resultI=new LINQ(data).Any( seekValue(19) );
console.log(resultI);
function seekValue( value) {
return function boundSeekValue( row ){
return row.indexOf( value ) != -1;
};
}
ES2016 has now Array.includes
which checks if a specific value exists in a Array. So if .Any
gives you Arrays you don't actually need to iterate those arrays you can do .includes
on the fly.
So you could compress your code to:
var data= [[2, 2, 3, 4, 5],[2, 2, 2, 6], [9], [13, 1,1,90]];
var LINQ = require('node-linq').LINQ;
var resultI = new LINQ(data).Any(row => row.includes(19));
Please note that having the 19
inside the code is not very good for code mantainance, its called "a magic number" since it appears in the middle of the code without explanation of where it comes from. But I suppose you will use a variable in its place.