Reputation: 23
I have one array like bellow :
array = [["127.0.0.1"],["127.0.0.1"],[],[]]
and want to extract one of the IPs , The problem is I want to recognize the difference between one element that has IP and empty elements,first I make a filter for recognize number but can't get the result now I trying this way :
let IpString = array.split("\"");
///and gave me this bellow result
Array(5) ["[[", "127.0.0.1", "],[", "127.0.0.1", "],[],[]]"]
browser_prototype.js:268
length:5
__proto__:Array(0) [, …]
0:"[["
1:"127.0.0.1"
2:"],["
3:"127.0.0.1"
4:"],[],[]]"
But I think I should find a way that can recognize between empty elements and IP elements then I need just one of the IP because always there are same and equal. I looking for this bellow result :
127.0.0.1
Upvotes: 0
Views: 71
Reputation: 8670
I'm not sure I get what your are trying to do, but you if you are sure your array will either be empty or have an IP in it, you might just have to check the length to see if there is anything in the array.
Here I'm using the filter
function. It takes a callback with an argument and expect the callback to return a boolean
const array = [["127.0.0.1"],["127.0.0.1"],[],[]];
// we use the filter function to check for the length of each sub-arrays.
// here, a length of 0 would evaluate as falsy, thus not including the empty array.
const ips = array.filter(item => item.length);
console.log(ips.length);
Optionally, thanks to blex's comment, you might want to map your multi-dimensionnal array to a single dimension. It's easier for comprehension. If so, check our their comment
Upvotes: 1