jquery grep, fitlering with regex - javascript

I will start this question with the statement that I'm really bad with regex.
Said this, I wonder if possible to filter an array using jquery $.grep, match strings with an specific string, something like this:
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
var s = a.split(",");
var array = $.grep(s, function(x, y) {
return ??????;
});
so after applying $.grep or any other function which could help, i will need the after ":" number of those with ABC, so my new array would be:
array[12, 2];
Any help with this??? I would really appreciate!

$.grep only select elements of an array which satisfy a filter function.
You need additional step to $.map all numbers from grepped array.
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
var b = $.grep(a, function(item) {
return item.indexOf("ABC:") >= 0;
});
var array = $.map(b, function(item) {
return item.split(":").pop();
});

Try
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
// map array ,
// test array items for "ABC" string ,
// filter `Number` in strings containing "ABC" ,
// return filtered Numbers , in newly mapped array
var s = $.map(a, function(n) {
return (/ABC/.test(n) ? Number(n.split(":").filter(Number)) : null)
}); // [12, 2]

Related

Checking if an array contains exactly a specific set of integers

Is that possible to check if the variable array contains exactly the numbers 1,0,0,1?
For example,
var array = [1,0,0,1];
if (array === 1001) alert("success");
You can just join the array to check
The join() method joins all elements of an array (or an array-like
object) into a string and returns this string.
Note: You need to use == instead of === because join will return a string.
Like:
var array = [1, 0, 0, 1];
if ( array.join("") == 1001 ) alert("success");
As per suggestion below, you can also use === and compare it with a string.
var array = [1, 0, 0, 1];
if ( array.join("") === "1001" ) alert("success");
Please check more info about join: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
Use the join() method to joins all elements of the array into a string and returns this string.
var elements = [1,0,0,1];
console.log(elements.join('') === "1001");
// expected output: true
Using the method join("") you conver your array into a string with out the commas
Then you use the includes("1001") to check for the expected result
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
var array = [1,0,0,1];
var string = array.join("");
console.log(string);
if (string.includes('1001')) alert("success");
Well, everyone gave a strict answer to your question; but I figured I would add on to it a little. Assuming you want this to be a little more dynamic. This way we check subsets of the array for the string you are looking for, rather than just the entire array.
Array.prototype.containsSequence = function(str, delimiter){
//Determines what is seperating your nums
delimiter = delimiter || '';
//Check the sub array by splicing it, then joining it
var checkSection = function (arr, start, end, str){
return arr.slice(start, end).join(delimiter) === str;
};
let start = 0; //start of our sub array
let end = str.length; //the length of the sub array
//Loop through each x size of sub arrays
while(end < this.length){
//Check the section, if it is true it contains the string
if(checkSection(this, start, end, str)){
return true;
}
//Incriment both start and end by 1
start++;
end++;
}
//We dont contain the values
return false;
};
///Test stuff
const ARRAY = [1,2,3,4,5,6,7,8,9,10];
if(ARRAY.containsSequence('456')){
console.log('It contains the str');
}else console.log('It does not contain');

Substring of a file

I have a file that is structure like this :
var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d";
Now I would extract all letters "c" and "d" of this file and put those letter in array, structure like this:
var array = [
[a,b,1],
[a,b,2],
[a,b,3],
[a,b,4],
[a,b,5]
];
How can I do that? It is possible?
--------------EDIT----------------------
And if I have an array structured like this?
exArray = [
["a":"one", "b":"two", "c":"three", "d":"four"],
["a":"five", "b":"six", "c":"seven", "d":"eight"]
];
The new array must be:
var array = [
[two,three,1],
[six,seven,2]
];
To get your desired output, this will do the trick:
var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d";
var array = file.split(", ") // Break up the original string on `", "`
.map(function(element, index){
var temp = element.split('|');
return [temp[0], temp[1], index + 1];
});
console.log(array);
alert(JSON.stringify(array));
The split converts your file string to an array like this:
["a|b|c|d", "a|b|c|d", "a|b|c|d", "a|b|c|d", "a|b|c|d"];
Then, map is called on that array, passing each "a|b|c|d", along with it's position in the array to the callback, which splits the string, and returns an array containing the first 2 elements, and it's id (index + 1).
You can also do the callback in the map slightly differently:
.map(function(element, index){
return element.split('|').slice(0, 2).concat(index + 1);
});
This method uses the same split, then uses slice to get the first 2 elements from the array, and concats the id to the array with 2 elements returned from slice.
This way, you don't use a temporary variable, there:
element // "a|b|c|d"
.split('|') // ["a", "b", "c", "d"]
.slice(0, 2) // ["a", "b"]
.concat(index + 1) // ["a", "b", id]
Try to use split() function and map() function
var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d";
file.split(',').map(function(el, index) {
var arr = el.split('|');
return [arr[0], arr[1], index+1]
});
If I understood you correctly, this should work:
function transformFile(file) {
return file.split(',').map(function(el) {
return el.split('|'); }
);
}
split() function transforms a string to an array taking its parameter as an item separator. You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
map() function takes an array and iterates over every item changing it in the way you define in the callback function. And here's the reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
So we're taking a string and first we split it in four arrays - each containing a|b|c|d string. Then we take each of those string and split it again (this time using | as separator) to transform a|b|c|d string into [a, b, c, d] array. So after those operations we end up with an array of arrays.
Try to use split() and replace() function.
var file = "a|b|c|d,a|b|c|d,a|b|c|d,a|b|c|d, a|b|c|d";
var NewFile =[];
var i = 1;
file.split(',').forEach(function(el) {
NewFile.push( el.replace("c|d", i).split("|"));
i++;
});
console.log(NewFile);

Split String into Array with RegEx Pattern

I have a string that I want to split into an array. The string looks like this:
'O:BED,N:KET,OT,N:JAB,FA,O:RPT,'
The string can contain any number of objects eg
'O:BED,N:KET,OT,N:JAB,FA,O:RPT,X:BLA,GTO'
I want to split this string on the instance of \w: eg O:
So I'll end up with array like this:
['O:BED','N:KET, OT','N:JAB,FA','O:RPT']
I am using the following code:
var array = st.split(/^(\w:.+)(?=\w:)/g);
However I end up with array like this :
['','O:BED,N:KET,OT,N:JAB,FA,','O:RPT,']
It seems the regex is being greedy, what should I do to fix it?
Note I am using angularjs and eventually I want to end up with this :
var objs = [
{type:O,code: BED, suf: ''},
{type:N, code: KET, suf: OT},
{type:N, code: JAB, suf: FA},
{type:O, code: RPT, suf: ''}
]
It would be much easier if your string is formatted properly. But still we can achieve the task with extra effort. Hope the below code works for you.
var str = 'O:BED,N:KET,OT,N:JAB,FA,O:RPT,X:BLA,GTO';
var a = str.split(',');
var objs = [], obj, item, suf;
for(var i=0; i<a.length;){
item = a[i].split(':');
if(a[i+1] && a[i+1].indexOf(':') == -1){
suf = a[i+1];
i++;
}else{
suf = "";
}
obj = {
type: item[0],
code: item[1],
suf: suf
};
objs.push(obj);
i++;
}
console.log(objs);
You can use the RegExp.prototype.exec method to obtain successive matches instead of splitting the string with a delimiter:
var myStr = 'O:BED,N:KET,OT,N:JAB,FA,O:RPT,';
var myRe = /([^,:]+):([^,:]+)(?:,([^,:]+))??(?=,[^,:]+:|,?$)/g;
var m;
var result = [];
while ((m = myRe.exec(myStr)) !== null) {
result.push({type:m[1], code:m[2], suf:((m[3])?m[3]:'')});
}
console.log(result);
You want to do a string match and then iterate over that.
Full example inside AngularJS: http://jsfiddle.net/184cyspg/1/
var myString = 'O:BED,N:KET,OT,N:JAB,FA,O:RPT,';
$scope.myArray = [];
var objs = myString.match(/([A-Z])\:([A-Z]*)\,([A-Z]?)/g);
objs.forEach(function (entry) {
var obj = entry.replace(',', ':');
obj = obj.split(':');
$scope.myArray.push({type: obj[0], code: obj[1], suf: obj[2]});
});
I love regular expressions :)
This will match each object of your string, if you want to use the global flag and exec() through all the matches:
(\w):(\w+)(?:,((?!\w:)\w+))?
The only real trick is to only treat the next bit after the comma as the suffix to this one if it doesn't look like the type of the next.
Each match captures the groups:
type
code
suf
If you just want to split as you said, then the solution to your greedy problem is to tell it to split on commas which are followed by those matching objects, eg:
,(?=(\w):(\w+)(?:,((?!\w:)\w+))?)
The following does not solve your regex issue however is an alternative approach to introduce underscorejs to handle from simple to more complex operations. Although an overkill in this case;
// ie. input string = 'O:BED,N:KET,OT,N:JAB,FA,O:RPT,';
.controller('AppCtrl', [function() {
/**
* Split by comma then (chain) eval each (map)
* element that (if-else) contains '0:' is pushed
* into array as a new element, otherwise concat element
*
* :#replace hardcoded values with params
*
* #param String string - a string to split
* #param String prefix - prefix to determine start of new array element ie. '0:'
* #param String delimiter - delimiter to split string ie ','
* #return Array array of elements by prefix
*/
$scope.splitter = function(string) {
var a = [];
var tmp = "";
_.chain(string.split(','))
.map(function(element) {
if(element.indexOf('O:') >= 0) {
element += tmp;
a.push(element);
tmp = "";
} else {
tmp += element;
}
});
return a;
};
}]);
Output:
array: Array[2]
0: "O:BED"
1: "O:RPTN:KETOTN:JABFA"
length: 2
Updated: Just read your requirements on Objects. underscorejs allows chaining operations. For example, the code above could be tweaked to handle Objects, chained to .compact().object().value() to produce output as Object k:v pairs;
Hope this helps.

Arrays and strings in javascripts

Array1 = ['1,2,3']
How can I retrieve the numerical values by transforming it into non-string?
I've been trying parseInt, but I can only manage to get 1 as end-result.
Thanks.
If you start with an array containing a string, like in your example, you need to use split().
Example:
Array1 = ['1,2,3'];
var new_array = Array1[0].split(','); // new_array is ["1", "2", "3"]
for (var i = 0; i < new_array.length; i++) {
new_array[i] = parseInt(new_array[i]);
}
// new_array is now [1, 2, 3]
I would re-look why you're storing a comma separated string as an array element; but, if the reasoning is valid for your particular design, the question is do you have an array with more than one comma-separated string like this?
If you can, re-work your design to actually use an array of integers, so use:
var arr = [1,2,3];
instead of ['1,2,3'].
If you are storing comma separated strings as array elements, you can get each index as an array of integers using something like the following:
var array1 = ['1,2,3', '4,5,6,7'];
function as_int_array(list, index) {
return list[index].split(',').map(function(o) { return parseInt(o,10); });
}
console.log("2nd element: %o", as_int_array(array1, 1));
// => 2nd element: [4,5,6,7]
Hope that helps.
Generally parseInt() takes anything(most of the time string) as input and returns integer out of that input. If it doesn't get any integer then it returns NaN.
Why you are getting 1 !!!
Whenever you are using parseInt() it tries to read your input character by character. So according to your input
var Array1 = ['1,2,3'];
first it get's '1' and after that ',' (a comma, which is not a number) so it converts '1' into Integer and returns it as your result.
Solution of your problem :
var Array1 = ['1,2,3'];
//just displayed the first element of the array, use for or foreach to loop through all the elements of the array
alert(Array1[0].split(',')[0]);

Javascript check every char in a string and return array element on corresponding position

Got a string that is a series of 0 or 1 bit and an array of values, if in the string are characters that are set to 1, I need to return the corresponding value from the array.
example: mystring = "0101"; myarray =["A","B","C","D"]; then result = "B,D"
how can I get this result?
for(var i=0;i<mystring.length;i++){
if(mystring[i] != 0)
{
result = myarray[i];
}
}
Your code seems to work just fine, so you can just add another array and push the values on to that:
var result = [];
for (var i = 0 ...
result.push(myarray[i]);
http://jsfiddle.net/ExplosionPIlls/syA2c/
A more clever way to do this would be to apply a filter to myarray that checks the corresponding mystring index.
myarray.filter(function (_, idx) {
return +mystring[idx];
})
http://jsfiddle.net/ExplosionPIlls/syA2c/1/
Iterate through the characters in the binary string, if you encounter a 1, add the value at the corresponding index in the array to a temporary array. Join the temporary array by commas to get the output string.
I am not really sure if this is what you are looking for, but this returns the array of matches.
var result = [];
for(var i=0;i<mystring.length;i++){
if(parseInt(mystring[i]) !== 0 ) {
result.push(myarray[i]);
}
}
return result;
result = new Array();
for(var i=0;i

Categories