Check if variable contains any value of array - javascript

I have two arrays like so;
arr1 = ["foo.com", "bar.com"],
arr2 = ["//test.net/index.html", "http://www.bar.com", "https://foo.com/example.js"]
I'm iterating through arr2 and I want to omit the ones that contain any value of arr1.
Currently I'm using indexOf but that doesn't work if the values don't match exactly.
$.each(arr2, function(k,v){
if(arr1.indexOf(v) == -1)
console.log(v);
});
I'd hope for the above code to output
//test.net/index.html
since it's the only value of arr2 that doesn't contain any value of arr1. What am I doing wrong?

I would wrote two each loops for this:
arr1 = ["foo.com", "bar.com"],
arr2 = ["//test.net/index.html", "http://www.bar.com", "https://foo.com/example.js"]
$.each(arr2, function(x,y){
var found = false;
$.each(arr1, function(k,v){
if(!(y.indexOf(v) == -1)){
found = true;
return false;
}
});
if(!found){
console.log(y);
}
found= false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

You can use filter + some ES5 Array methods:
var arr1 = ["foo.com", "bar.com"],
arr2 = ["//test.net/index.html", "http://www.bar.com", "https://foo.com/example.js"];
var result = arr2.filter(function(val) {
return !arr1.some(function(el) {
return val.indexOf(el) !== -1;
});
});
alert(result);
Support for ES5 starts from IE9+, but if you need it to work in older IE, you can use polyfills (see links I provided), or it's pretty trivial to rewrite some part with simple for loop and use $.grep instead of Array.prototyp.filter.

It seems That you're using the Array version of indexOf, which doesn't work id the match is not exact.
With a little bit more setup, you can use the String version of indexOf
function compareValues (arr1, arr2){
var res = false;
$.each(arr2, function(k,v) {
checkAgainstArray(arr1, v);
});
function checkAgainstArray(arr1, value) {
$.each(arr1, function(k, v) {
if(value.indexOf(v) !== -1){
res = true;
}
});
}
return res;
}
//later on
var isValueInArray = compareValues(arr1, arr2);
(the code is not tested), but I Hope this helps

Try use the javascript RegExp to do the matching for each array element
http://www.w3schools.com/js/js_regexp.asp

Related

An if loop omitting an array

I have an array of strings like thisvar arr = ['BUTTON','BADGE','CHECKBOX]'
Now I need a if condition to be written for the strings except those present in the array. How do I do that??
I'm a beginner and know nothing much about javascript. Thanks in advance for your help.
I tried var arr = ['BUTTON','BADGE','CHECKBOX];
if(!arr){
//code to be executed
}
However this always returns false.
You can use indexOf:
if(arr.indexOf(test_variable) === -1){
// element doesn't exist in array
}
I don't really understand your question but maybe array.some can solve your problem:
var someString = 'BADGE';
var arr = ['BUTTON','BADGE','CHECKBOX' ];
if (arr.some(str => str === someString)) {
console.log("Exist");
} else {
console.log("Doesn't exist");
}
This is how to do it:
var pippo = "pippo";
var arr = ['BUTTON','BADGE','CHECKBOX'];
if(arr.indexOf(pippo) > -1){
console.log("contained!");
}
else{
console.log("not contained!");
}
First of all the last element of your array/list is not properly written as a string i.e 'CHECKBOX. You missed a single quote in the end so it should be 'CHECKBOX'
var arr = ['BUTTON','BADGE','CHECKBOX];
↓
var arr = ['BUTTON','BADGE','CHECKBOX'];
Secondly coming to your actual query, according to your question it seems you want to run a piece of code if a string is not present in the array.
For this, you can use the array.indexOf() function which returns the position/index of the variable in the array passed as a parameter to it & if the variable is not present in the array, it returns a value of -1
More about this:- https://www.w3schools.com/jsref/jsref_indexof_array.asp
So the code for that would be:-
var arr = ['BUTTON','BADGE','CHECKBOX'];
var str = 'foo'; //string not present in the array i.e arr
if(arr.indexOf(str) === -1) {
//your code here
}
length will works for you if comes 0, return 0 when not element exists in the arrayset
var arr = ['BUTTON','BADGE','CHECKBOX'];
console.log(arr.length)

How do I filter items in an array based on a substring match?

I am searching an array in jQuery,
var arr = ["mango","banana","jackfriut","apple","google"];
var removeItem = "google"; //works fine
var removeItem = "ogle"; //fails
arr = $.grep(arr, function(value) {
return value != removeItem;
});
alert(arr)
When I am passing "google" then its working fine.
Please let me know that it should work when I pass only some content like "ogle".
its like wildcard.
You can use indexOf for your condition
var arr = ["mango","banana","jackfriut","apple","google"];
var removeItem = "ogle"; //fails
arr = $.grep(arr, function(value) {
if(value.indexOf(removeItem) == -1)
return value;
});
alert(arr)
JSFiddle
Hope it helps :)
You can use jQUery's built in $.inArray function.
var arr = ["mango","banana","jackfriut","apple","google"];
function inArray() {
if($.inArray(value, arrayName) !== -1) {
alert("Value is in array");
} else {
alert("Value is not in array");
}
}
You can then call your function passing in the value you are looking for:
inArray("google");
Of course, the logic you choose to return in the function is up to you but this is the best way to check for values in an array.

easiest way to see if array has array? Javascript

the only way I can think to do this is to do something like:
for current array length,
for array to check length
if current array i === array to check i
true
Essentially I have the following:
arr = [[1,2], [0,3]];
When I want to add another array to this arrays: [1,2] I need to first see if it exists, if it does do not push it on to the array, if it doesn't then push it.
Is there some really simple, clean readable way to check if an array exists in an array of arrays before pushing it on to the list of elements?
Update:
it should be pretty simple, you have array:
arr = [[1,2], [0,3]];
You try and push:
[1,2]
Nothing happens.
You try and push: [4,6]. New array: [[1,2], [0,3], [4,6]];
Since the complexity is limited, a simple solution exists:
function maybePush(to, val) {
if(!to.some(function(curr) {
return curr.length !== val.length ||
curr.some(function(v, i) { return val[i] === v; });
})) {
to.push(val);
}
}
arr = [[1,2], [0,3]];
maybePush(arr, [1,2]);
maybePush(arr, [5,6]);
console.log(arr);
You'd probably want to add some guards, check that what you expect to be an array really is an array and so on (left out for clarity)...
The idea is simple, check if any of the values of the outer array is equal to the val array, using an iterative comparison.
If you know your array arr contains only integers and arrays, a simple check to see if the array matches the flattened array will indicate if the array contains inner arrays.
var arr = [1,2,3,[4,5],6];
if (JSON.stringify(arr) === JSON.stringify([].concat.apply([], arr))) {
// Does not contain an array
}
The snippet [].concat.apply([], arr) flattens the array arr.
Using underscore you can do this:
Initial approach:
var i = _.findIndex(arr, function (e) {
return (e.join(',') === arr_elem.join(','));
});
if (i === -1) {
arr.push(arr_elem);
}
EDIT Considering performance (Also read the comments here), it would be better to check array equality using a brute loop approach:
function arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
return true;
}
var i = _.findIndex(arr, function (e) {
return arraysEqual(arr_elem, e);
});
if (i === -1) {
arr.push(arr_elem);
}

This simple comparison of jQuery objects does not compare

Curious what I'm doing wrong here :
employee_ids = $('[data-employee_id="'+employee+'"]');
timestamp_ids = $('[data-scheduled_on="'+timestamp+'"]');
var common = $.grep(timestamp_ids, function(element) {
$.each(employee_ids, function(idx, item) {
if ( item === element ) { console.log ("omg!") };
});
});
This returns just the list of timestamp_ids and not that array compared against employee_ids looking for a single match.
You are not using .grep correctly. Each iteration of grep should return a boolean: true to add it to the result array, false to ignore it.
var listA = [1, 2, 3];
var listB = [2, 3, 4];
var union = $.grep(listA, function (element) {
return listB.indexOf(element) !== -1;
});
Note that IE does not support .indexOf on Arrays, you will have to implement the comparison some other way.
EDIT: if you are trying to find a single item of an array that matches some criteria, i would suggest just using a regular for loop:
var result;
for (var i = 0; i < yourArray.length; i++) {
if (yourArray[i].id === employee_ID) { // whatever conditions you have
result = yourArray[i];
break;
}
}
if (result) {
// do whatever
} else {
// no match
}
Whatever else is wrong with that, it looks like the error is happening at $.grep
What is the typeof of timestamp_ids? According to the jQ docs, it needs to be an array.
Will this work?
employee_ids = $('[data-employee_id="'+employee+'"]');
timestamp_ids = $('[data-scheduled_on="'+timestamp+'"]');
var common = $.grep(timestamp_ids, function(element) {
return !($.inArray(element, timestamp_ids) == -1)
});
Whoa! Thanks for everyone's help. I just realized I could do this :
$('[data-employee_id="'+employee+'"][data-scheduled_on="'+timestamp+'"]');
I also realized I'm an idiot :(

how to prevent adding duplicate keys to a javascript array

I found a lot of related questions with answers talking about for...in loops and using hasOwnProperty but nothing I do works properly. All I want to do is check whether or not a key exists in an array and if not, add it.
I start with an empty array then add keys as the page is scrubbed with jQuery.
Initially, I hoped that something simple like the following would work: (using generic names)
if (!array[key])
array[key] = value;
No go. Followed it up with:
for (var in array) {
if (!array.hasOwnProperty(var))
array[key] = value;
}
Also tried:
if (array.hasOwnProperty(key) == false)
array[key] = value;
None of this has worked. Either nothing is pushed to the array or what I try is no better than simply declaring array[key] = value Why is something so simple so difficult to do. Any ideas to make this work?
Generally speaking, this is better accomplished with an object instead since JavaScript doesn't really have associative arrays:
var foo = { bar: 0 };
Then use in to check for a key:
if ( !( 'bar' in foo ) ) {
foo['bar'] = 42;
}
As was rightly pointed out in the comments below, this method is useful only when your keys will be strings, or items that can be represented as strings (such as numbers).
var a = [1,2,3], b = [4,1,5,2];
b.forEach(function(value){
if (a.indexOf(value)==-1) a.push(value);
});
console.log(a);
// [1, 2, 3, 4, 5]
For more details read up on Array.indexOf.
If you want to rely on jQuery, instead use jQuery.inArray:
$.each(b,function(value){
if ($.inArray(value,a)==-1) a.push(value);
});
If all your values are simply and uniquely representable as strings, however, you should use an Object instead of an Array, for a potentially massive speed increase (as described in the answer by #JonathanSampson).
A better alternative is provided in ES6 using Sets. So, instead of declaring Arrays, it is recommended to use Sets if you need to have an array that shouldn't add duplicates.
var array = new Set();
array.add(1);
array.add(2);
array.add(3);
console.log(array);
// Prints: Set(3) {1, 2, 3}
array.add(2); // does not add any new element
console.log(array);
// Still Prints: Set(3) {1, 2, 3}
If you're already using spread...
let colors = ['red', 'orange', 'yellow'];
let moreColors = ['orange', 'green'];
let mergedColors = [...colors, ...moreColors];
and want to avoid duplicates...
let mergedColors = [...colors, ...moreColors.filter(c => !colors.includes(c)) ];
You can try this:
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
Easiest way to find duplicate values in a JavaScript array
The logic is wrong. Consider this:
x = ["a","b","c"]
x[0] // "a"
x["0"] // "a"
0 in x // true
"0" in x // true
x.hasOwnProperty(0) // true
x.hasOwnProperty("0") // true
There is no reason to loop to check for key (or indices for arrays) existence. Now, values are a different story...
Happy coding
function check (list){
var foundRepeatingValue = false;
var newList = [];
for(i=0;i<list.length;i++){
var thisValue = list[i];
if(i>0){
if(newList.indexOf(thisValue)>-1){
foundRepeatingValue = true;
console.log("getting repeated");
return true;
}
} newList.push(thisValue);
} return false;
}
var list1 = ["dse","dfg","dse"];
check(list1);
Output:
getting repeated
true
let x = "farceus";
let y = "character";
const commonCharacters = function (string1, string2) {
let duplicateCharacter = "";
for (let i = 0; i < string1.length; i += 1) {
if (duplicateCharacter.indexOf(string1[i]) === -1) {
if (string2.indexOf(string1[i]) !== -1) {
duplicateCharacter += string1[i];
}
}
}
return [...duplicateCharacter];
};
console.log(commonCharacters(x, y));

Categories

Resources