I have an array that is made of three arrays.
I have a value (an array, '[7,5]') that I want to check through the arrays for.
https://jsfiddle.net/qx4wLf4f/6/
var arrays = [];
var arrayOne = [ [1,3], [2,3], [2,4] ];
var arrayTwo = [ [7,6], [7,5], [7,4] ];
var arrayThree = [ [3,3], [3,2], [2,2] ];
arrays.push( arrayOne, arrayTwo, arrayThree );
function checkArraysForValue( val ){
if( !$.isArray(val) ){
$('#result').html('Not Array');
return false;
}
var found = 'not found';
arrays.forEach(function( item, index ){
if( item.indexOf( val ) > -1 ){
found = 'did find';
}
});
$('#result').html(found);
}
checkArraysForValue( [7,5] );
For your specific scenario, just JSON.stringify
and indexOf
will do
var isPresent = JSON.stringify( arrays ).indexOf( JSON.stringify( val ) ) != -1;
Demo
var arrays = []; var arrayOne = [ [1,3], [2,3], [2,4] ]; var arrayTwo = [ [7,6], [7,5], [7,4] ]; var arrayThree = [ [3,3], [3,2], [2,2] ]; arrays.push( arrayOne, arrayTwo, arrayThree ); function checkArraysForValue( val ) { //console.log( JSON.stringify( arrays ) ); //console.log( JSON.stringify( val ) ); return JSON.stringify( arrays ).indexOf( JSON.stringify( val ) ) != -1 ? "Found" : "Not Found"; } console.log(checkArraysForValue( [7,5] ));
function isArrayIdentical(arr1, arr2){
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;){
if(arr1[i] !== arr2[i])
return false;
}
return true;
}
this is the function which you need to work with, i have included a fiddle for the implemented solution to your question below. https://jsfiddle.net/2r4y9mr9/
basically, you can also stringify your sample for performing string matching in the answer but then, solution will not be correct if "1" and 1 is different in your consideration.
array.forEach()
doesn't work like you think. Here my jsFiddle to exaplain what this method does. I solved your problem with this but it's not efficient.
var arrays = [];
var arrayOne = [
[1, 3],
[2, 3],
[2, 4]
];
var arrayTwo = [
[7, 6],
[7, 5],
[7, 4]
];
var arrayThree = [
[3, 3],
[3, 2],
[2, 2]
];
arrays.push(arrayOne, arrayTwo, arrayThree);
function isEqual(arr1, arr2) {
if (arr1.length !== arr2.length)
return false;
for (var i = arr1.length; i--;) {
if (arr1[i] !== arr2[i])
return false;
}
return true;
}
function checkArraysForValue(val) {
if (!$.isArray(val)) {
$('#result').html('Not Array');
return false;
}
var val = val;
var found = 'not found';
for(var i = 0; i < arrays.length; i++){
for(var j = 0; j < arrays[i].length; j++){
if(isEqual(arrays[i][j],val)){
found = 'did found';
}
}
}
$('#result').html(found);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.