find a specific string pattern in an array jquery - javascript

Apologies if this is a duplicate, but I can't seem to find the solution.
I am trying to find a specific string pattern in an array.
I want to find all values in data that contain 'underscore r underscore'. I then want to create a new array that contains only those keys and values.
var data = ["something", "bar_r_something"];
var resultArray = new Array();
for (var i = 0; i < data.length; i++) {
var bar = /_r_/;
if ($.inArray(bar, data[i].length) > 0)
{
console.log("found _r_");
resultArray.push(data[i]);
}
};
I just can't seem to get that $.inArray to work, it seems to always kick out -1.

var data = ["something", "bar_r_something"];
var resultArray = new Array();
for (var i = 0; i < data.length; i++) {
var bar = /_r_/;
if (bar.test(data[i])) {
alert("found _r_");
resultArray.push(data[i]);
}
};
console.log(resultArray);
Here you go, it doesn't use $.inArray, but Regex instead, hope that's cool!
EDIT
If you wanted to go a bit more fancy, you can use JavaScript's filter method like so:
var data = ["something", "bar_r_something"];
var resultArray = data.filter(function(d){
return /_r_/.test(d);
});
console.log(resultArray);

I think what you are looking for is $.grep(). Also $.inArray() does not test the values against a regex, it tests for equality.
var regex = /_r_/
var resultArray = $.grep(data, function(item){
return regex.test(item)
})
Demo: Fiddle

Related

Use filter method on multidimensional arrays in JavaScript

Having a multidimensional array, I would like to filter it, so only the array which has a word ending with underscore '_' is left. I have already accomplished this task using loops.
function searchNames( logins ){
var arr = logins;
var reg = /\w+_\b/;
var newAr = [];
for(var i = 0; i < arr.length; i++) {
for(var x = 0; x < arr[i].length; x++){
if(arr[i][x].match(reg)){
newAr.push(arr[i])
}
}
}
return newAr;
}
Is there any way to do the same using
Array.prototype.filter() method. According to MDN reference (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) you can do similar things but I can`t figure out how to filter the arrays inside the array. All of my attempts to use filter method inside of another filter method failed.
Just pass the filter method a useful block:
array = [["hello_","cat"],["dog","dog"]];
arrayTest = function(arr){
resp = false;
arr.forEach(function(str){
if(str.slice(-1) === "_") resp = true;
});
return resp;
}
result = array.filter(arrayTest);
or if you're really married to your regex:
array = [["hello_","cat"],["dog","dog"]];
regex = /\w+_\b/;
arrayTest = function(arr){
resp = false;
arr.forEach(function(str){
if(str.match(regex)) resp = true;
});
return resp;
}
result = array.filter(arrayTest);
You seem to want
var newArr = arr.filter(subArr => subArr.some(e=>/\w+_\b/.test(e)));

jQuery or JavaScript compare two arrays one contains an object

MyIds has just two Id numbers 1 and 2
var MyIds = [1,2]
but MyObject has three Id numbers 1, 2 and 3 (In reality this has about 500 Id's)
var MyObject = [{id:1,size:21,length:31},{id:2,size:22,length:32},{id:3,size:23,length:33}]
and I want to make a new variable that looks like this, I need some magic code that will compare the two variables and only return the details of the objects where the Is's match
var Result = [{id:1,size:21,length:31},{id:2,size:22,length:32}]
I'm happy to use jQuery if it help
Use Array.prototype.filter()
var Result = MyObject.filter(function(item){
return MyIds.indexOf(item.id) >-1;
});
It can be easily solved with underscore or lodash with something like:
Result = _.filter(MyObject, function (item) {
return _.indexOf(item.id, MyIds) !== -1;
});
I admit, this is a lazy answer. There is probably a way to make it without adding a news library. But lodash is so cool :)
It can be done without jQuery:
var MyIds = [1,2];
var MyObject = [{id:1,size:21,length:31},{id:2,size:22,length:32},{id:3,size:23,length:33}];
var Result = [];
MyObject.forEach(function(element) {
MyIds.forEach(function(id){
if(element.id == id)
Result.push(element);
});
});
A more diverse sollution without using any library:
function find(propName, filters, collection){
var temp = [];
for(var i = 0; i < collection.length; i++){
for(var j = 0; j < filters.length; j++){
if(collection[i][propName] === filters[j]){
temp.push(collection[i]);
break;
}
}
}
return temp;

How can I get a specific part of element in arrays

The title may a little confusing. But i think it is clear:
var a = ["A1", "B13", "C123"];
I want to ignore first value in elements and get rest of them. So my new array should look like this:
var b = ["1", "13", "123"];
Use .map() to create a new Array of modified values of the original.
var b = a.map(function(item) {
return item.slice(1);
});
This iterates the original Array, passes each item in the Array as the first argument to the function, and sets the return value of the function as the values for the new Array.
For IE8 and lower, you'll need to implement a patch. One is available from MDN.
Using .map, you can return a new array which is generated by passing every element in the existing array through a function:
var b = a.map(function(v) {
return v.substr(1);
});
Note that .map is an ES5 function that doesn't exist on older browsers. A shim is available at the above link.
var b = [];
for (var i = 0; i < a.length; ++i)
{
b[i] = a[i].substring(1);
}
Live Demo
The forEach way
var a = ["A1", "B13", "C123"],
b = [];
a.forEach(function (element) {
b.push(element.slice(1));
});
console.log(b);
on jsfiddle
The map way
var b = a.map(function (element) {
return element.slice(1);
});
The for way
var l = a.length;
var b = [];
for (var i = 0; i < l; i += 1) {
b.push(a[i].slice(1));
}
Ultimate speed is still the for loop (except for maybe grand daddy)
So as I ended up including all of the above, it didn't feel right to leave the grand daddy of them all out of the equation.
The while way
var b = [];
var i = 0;
var l = a.length;
while (i < l) {
b.push(a[i].slice(1));
i += 1;
}
I also include a RegExp and jquery version for a bit of a giggle.
(lodash also has it's own map function)
You can see the jsperf

Transform a string into an array of arrays in JavaScript

I'm searching the shortest method to transform a string like
"str1,str2,str3,..."
into an array of arrays like :
[["str1"], ["str2"], ["str3"]]
I could use a loop or an each, but I wonder if there is something more elegant.
You can make use of split() and map() like so:
// This could be turned into 1 line but is split here for readibility
var array = string.split(',');
array = array.map(function(value){
return [value];
});
Note: map() doesn't exist in all implementations, check out this article for more info on it.
If you are targeting an ES5 supporting browser you could use Array.map.
var array = "str1,str2,str3".split(",").map(function(token) {
return [token]
});
Tom Walter's answer is great, but in case you don't want to use map:
var str = "str1,str2,str3";
var arr = str.split(",");
var arrOfarrs = [];
for(var i = 0; i < arr.length; i++) {
arrOfarrs.push([arr[i]]);
}
Alternatively, you can add a map polyfill to add support for older browsers:
Array.prototype.map = Array.prototype.map || function(fn) {
var arr = [];
for(var i = 0; i < this.length; i++) {
arr.push(fn(this[i]));
}
return arr;
};
which would then allow you to do
var arr = str.split(",").map(function(val) {
return [val];
});

Extract specific substring using javascript?

If I have the following string:
mickey mouse WITH friend:goofy WITH pet:pluto
What is the best way in javascript to take that string and extract out all the "key:value" pairs into some object variable? The colon is the separator. Though I may or may not be able to guarantee the WITH will be there.
var array = str.match(/\w+\:\w+/g);
Then split each item in array using ":", to get the key value pairs.
Here is the code:
function getObject(str) {
var ar = str.match(/\w+\:\w+/g);
var outObj = {};
for (var i=0; i < ar.length; i++) {
var item = ar[i];
var s = item.split(":");
outObj[s[0]] = s[1];
}
return outObj;
}
myString.split(/\s+/).reduce(function(map, str) {
var parts = str.split(":");
if (parts.length > 1)
map[parts.shift()] = parts.join(":");
return map;
}, {});
Maybe something like
"mickey WITH friend:goofy WITH pet:pluto".split(":")
it will return the array, then Looping over the array.
The string pattern has to be consistent in one or the other way atleast.
Use split function of javascript and split by the word that occurs in common(our say space Atleast)
Then you need to split each of those by using : as key, and get the required values into an object.
Hope that's what you were long for.
You can do it this way for example:
var myString = "mickey WITH friend:goofy WITH pet:pluto";
function someName(str, separator) {
var arr = str.split(" "),
arr2 = [],
obj = {};
for(var i = 0, ilen = arr.length; i < ilen; i++) {
if ( arr[i].indexOf(separator) !== -1 ) {
arr2 = arr[i].split(separator);
obj[arr2[0]] = arr2[1];
}
}
return obj;
}
var x = someName(myString, ":");
console.log(x);

Categories

Resources