I have two multidimensional array and i want to create a third multidimensional array:
var reports = [
[48.98,153.48],
[12.3,-61.64]
];
var vulc = [
["ciccio",48.98,153.48],
["cicci",12.3,-61.64],
["intruso",59.9,99.9]
];
And i want to create a new multidimensional array
var nuovarray= [];
for (i=0; i<= reports.length; i++) {
var attivi= reports[i];
var attlat= attivi[0];
var attlng= attivi[1];
for (s=0; s<=vulc.length; s++){
var vulca= vulc[s];
var vulcanam= vulca[0];
var vulcalat= vulca[1];
var vulcalng= vulca[2];
if ((vulcalat==attlat) && (vulcalng==attlng){
var stato= "A";
nuovarray.push([vulcanam,vulcalat,vulcalng,stato]);
}
else{
var stato= "N";
nuovaarray.push([vulcanam,vulcalat,vulcalng,stato]);
}
}
}
i would like to have
var nuovarray= [
["ciccio",48.98,153.48,"N"],
["cicci",12.3,-61.64,"N"],
["intruso",59.9,99.9,"A"]
];
But i don't know if this code is good :/
As I said in the comment, in the for loop, use < not <= (array of length N has indexes 0 ... N-1) ... and swap the outer loop with the inner loop, and only push with value 'N' before the end of the outer loop if the inner loop hasn't pushed with value 'A'
var reports = [
[48.98,153.48],
[12.3,-61.64]
];
var vulc = [
["ciccio",48.98,153.48],
["cicci",12.3,-61.64],
["intruso",59.9,99.9]
];
var nuovarray= [];
for(var s = 0; s < vulc.length; s++) {
var vulca = vulc[s];
var stato= "A"; // default, no match
var vulcanam= vulca[0];
var vulcalat= vulca[1];
var vulcalng= vulca[2];
for(var i = 0; i < reports.length; i++) {
var attivi = reports[i];
var attlat= attivi[0];
var attlng= attivi[1];
if ((vulcalat==attlat) && (vulcalng==attlng)) {
stato = "N";
break; // we've found a match, so set stato = N and stop looping
}
}
nuovarray.push([vulcanam,vulcalat,vulcalng,stato]);
}
document.getElementById('result').innerHTML = (nuovarray).toSource();
<div id='result'></div>
I believe the code will not work the way it is written. At least, it will not give you the expected output. You are iterating through the vulc array inside the loop which iterates through reports. And you are pushing to the nuovarray inside the inner loop. So I would expect 6 elements in nuovarray, not the 3 elements you are expecting.
Did you try running it? That's the easiest way to prove incorrectness.
var reports = [
[48.98,153.48],
[12.3,-61.64]
];
var vulc = [
["ciccio",48.98,153.48],
["cicci",12.3,-61.64],
["intruso",59.9,99.9]
];
var nuovarray = [];
vulc.forEach(function(item, indx){
var bN = 'undefined' !== typeof reports[indx];
bN = bN && item[1] == reports[indx][0] && item[2] == reports[indx][1];
item.push(bN ? 'N' : 'A');
nuovarray.push(item);
});
console.log(nuovarray);
The code maps the given vulc to nuovarray and add the wanted flag to it. The flag is selected by a search over reports and if found, an 'N' is applied, otherwise an 'A' is applied.
var reports = [
[48.98, 153.48],
[12.3, -61.64]
],
vulc = [
["ciccio", 48.98, 153.48],
["cicci", 12.3, -61.64],
["intruso", 59.9, 99.9]
],
nuovarray = vulc.map(function (a) {
a.push(reports.some(function (b) {
return a[1] === b[0] && a[2] === b[1];
}) ? 'N' : 'A')
return a;
});
document.getElementById('out').innerHTML = JSON.stringify(nuovarray, null, 4);
<pre id="out"></pre>
The map() method creates a new array with the results of calling a provided function on every element in this array.
Array.prototype.map()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
Array.prototype.push()
The some() method tests whether some element in the array passes the test implemented by the provided function.
Array.prototype.some()
var reports = [
[48.98,153.48],
[12.3,-61.64]
];
var vulc = [
["ciccio",48.98,153.48],
["cicci",12.3,-61.64],
["intruso",59.9,99.9]
];
console.log(vulc.map(function (item, index) {
item.push(reports.some(function (report) {
return report[0] == item[1] && report[1] == item[2];
})?"N":"A");
return item;
}));
If performance matters, you should use something better than O(n^2):
var existingPoints = {};
reports.forEach(function (row) {
existingPoints[row.join()] = true;
});
var nuovarray = vulc.map(function (row) {
var point = row.slice(1, 3).join();
var flag = existingPoints[point] ? 'A' : 'N';
return row.concat([flag]);
});
Related
Here is my code:
var subMed = [ {med:'bm', sub:[ 'a' , 'b' ]} , {med:'bm', sub:[ 'c' , 'd' , 'e' ]} ];
var sal = [ {num:"1",amount:"500"} ];
var t = {Class:"1", subMeds:subMed, numOfSub:2, sals:sal };
var infoAcademic = [];
infoAcademic.push(t);
subMed = [ {med:'em', sub:[ 'p']} , {med:'bm', sub:[ 'r' , 's' ]} ];
sal = [ {num:"2",amount:"1500"},{num:"1",amount:"700"} ];
t = {Class:"1", subMeds:subMed, numOfSub:1, sals:sal };
infoAcademic.push(t);
var tempObj = infoAcademic[1]; // an object
var mediumSubjects = tempObj["subMeds"]; // an array
console.log(mediumSubjects);
for(i=0;i<mediumSubjects.length;i++){
var temp = {}; // object
temp = mediumSubjects[i];
if(temp["med"] == 'bm'){
tempObj["numOfSub"] = tempObj["numOfSub"] - temp["sub"].length;
var salArr = tempObj["sals"]; // array
var j = salArr.length;
if(salArr.length > 0){
while(j--){
var salObj = salArr[j]; // object
var howManySub = salObj["num"];
if(howManySub > tempObj["numOfSub"]){
salArr.splice(j,1);
}
}
}
console.log("removing from the medSubjects list: ");
console.log(temp);
var removed = mediumSubjects.splice(i, 1);
break;
}
}
console.log("removed element: ");
console.log(removed);
console.log(mediumSubjects);
When I write this code this an online js editor https://js.do/ , the code gives result as per expected. But when I incorporate this code in a onclick function of my JSP page, no element gets removed from the mediumSubjects array. The removed element shows empty.
However, when I comment out this portion:
tempObj["numOfSubj"] = tempObj["numOfSub"] - temp["sub"].length;
var salArr = tempObj["sals"]; // array
var j = salArr.length;
if(salArr.length > 0){
while(j--){
var salObj = salArr[j]; // object
var howManySub = salObj["num"];
if(howManySub > tempObj["numOfSub"]){
salArr.splice(j,1);
}
}
}
the code surprisingly behaves as expected- it removes the element from the mediumSubjects array.
Is there any synchronization issue or something else? Why this sort of unusual behavior?
N.B. I need to remove elements from the array mediumSubjects, so delete won't work here.
Try this variant:
var newMedSub = medSub.filter(function(elem) {
return elem.med !== 'em';
});
It will help you to get a new array without unnessessary object.
All you actually need is to iterate over the outer array and in the body of this loop you need to iterate over the object keys.
for Example:
// removing med key from the array.
medSub.forEach(obj => {
for (let key in obj) {
if (key === 'med' && obj[key] === 'em') {
delete obj[key];
}
}
});
I hope this helps.
I'm pretty new in js, I have an array that looks like this:
[ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,off',
'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on'
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off',
'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxyear,SEzlksdfMpksfhksfMmqkPczCl2,off' ]
How can I delete the rows from the array that has:
-> the last value "off" AND the first two values the same as a line with the "on" value
like this:
(*) [ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on',
'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxyear,SEzlksdfMpksfhksfMmqkPczCl2,off' ]
So I was like:
var productIds = [];
var userIds = [];
var status = [];
unique.forEach(function(data) {
var dataArray = data.split(',');
productIds.push(dataArray[0]);
userIds.push(dataArray[1]);
status.push(dataArray[2]);
});
for (var h = 0; userIds.length >= h; h++) {
if (status[h] == "on") {
for (var k = 0; userIds.length >= k; k++) {
if (status[k] == "off" &&
userIds[h] == userIds[k] &&
productIds[h] == productIds[k]) {
delete status[k];
delete userIds[k];
delete productIds[k];
}
}
}
}
But I think it is so much code... and well, just the forEach is the one working fine (separating into three objects) And the for loops I think work wrong because forEach is async. So is there any way I could improve the code to get that output mentioned (*)?
After this I need to send the array with the off rows that were left.
You can use Array filter.
Here an example:
var array = ['com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on', 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,off', 'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on', 'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on', 'com-fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off', 'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on'];
function checkFilter(str) {
return str.indexOf('off') !== str.length - 3 || str.indexOf('co') !== 0;
}
function myFunction() {
document.getElementById("demo").innerHTML = array.filter(checkFilter);
}
You can test this code here http://www.w3schools.com/code/tryit.asp?filename=FBN71QBHVUS1
The doc http://www.w3schools.com/jsref/jsref_filter.asp
var data = ['com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,off',
'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on',
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off',
'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxyear,SEzlksdfMpksfhksfMmqkPczCl2,off'
];
// es6
// var output = data.filter(d => !(d.endsWith('off') && data.find(val => val.endsWith('on') && val.startsWith(d.substr(0, d.length - 3)))));
// es5
var output = data.filter(function(d) {
return !(d.indexOf('off') === d.length - 3 && data.filter(function(val) {
return val.indexOf('on') === val.length - 2 && val.indexOf(d.substr(0, d.length - 3)) === 0
}).length);
});
console.log(output);
If your array is not too long (if the efficiency is not so critical) then you can hack the .sort() function of the Array and get your desired output.
var arr = [ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,off',
'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on',
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off',
'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxyear,SEzlksdfMpksfhksfMmqkPczCl2,off' ];
var removeOffOrOnFromStr = function(str){
return str.split(",", 2).toString()
}
var removeOffFromArray = function(arr, first, second){
var off = first;
if(second[second.length - 1] == "f"){
off = second;
}
arr.splice(arr.indexOf(off), 1)
}
var filtered = arr.slice()
arr.sort(function(first, second){
var removedOnOrOff1 = removeOffOrOnFromStr(first)
var removedOnOrOff2 = removeOffOrOnFromStr(second)
var thirdValueDiff = false
if(first[first.length - 1] != second[second.length - 1]){
thirdValueDiff = true
}
if(removedOnOrOff1 == removedOnOrOff2 && thirdValueDiff ){
removeOffFromArray(filtered, first, second)
}
});
console.log(filtered)
You may use Array.filter() method.
Please find details here
MDN Array filter method.
edit: I did miss your second requirement, now fixed, still using filter plus a (very) small bit of regex:
var target = [ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on', 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,off', 'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on', 'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off', 'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxyear,SEzlksdfMpksfhksfMmqkPczCl2,off' ];
var withOn = target.filter(function(el){return /on$/.test(el)});
var filteredResult = target.filter(
function(el){
var valueToMatch= el.match(/.*(?=,)/);//everything up to last comma
return !(/off$/.test(el) && withOn.filter(function(el){ return el.match(valueToMatch);}).length>0);//check for ending with 'off' and that one of the 'ons' has the same value
});
console.log(filteredResult);
Let's say we have the following js array
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var val = [3,566,23,79];
Is there a js builtin function or jQuery one with which you can search the array ar for val?
Thanks
***UPDATE*************
Taking fusion's response I created this prototype
Array.prototype.containsArray = function(val) {
var hash = {};
for(var i=0; i<this.length; i++) {
hash[this[i]] = i;
}
return hash.hasOwnProperty(val);
}
you could create a hash.
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var hash = {};
for(var i = 0 ; i < ar.length; i += 1) {
hash[ar[i]] = i;
}
var val = [434,677,9,23];
if(hash.hasOwnProperty(val)) {
document.write(hash[val]);
}
You can also use a trick with JSON serializing. It is short and simple, but kind of hacky.
It works, because "[0,1]" === "[0,1]".
Here is the working demo snippet:
Array.prototype.indexOfForArrays = function(search)
{
var searchJson = JSON.stringify(search); // "[3,566,23,79]"
var arrJson = this.map(JSON.stringify); // ["[2,6,89,45]", "[3,566,23,79]", "[434,677,9,23]"]
return arrJson.indexOf(searchJson);
};
var arr = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
document.body.innerText = arr.indexOfForArrays([3,566,23,79]);
function indexOfArray(val, array) {
var hash = {};
for (var i = 0; i < array.length; i++) {
hash[array[i]] = i;
}
return (hash.hasOwnProperty(val)) ? hash[val] : -1;
};
I consider this more useful for than containsArray(). It solves the same problem (using a hash table) but returns the index (rather than only boolean true/false).
Can you try this?
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var val = [3,566,23,79];
var sval = val.join("");
for(var i in ar)
{
var sar = ar[i].join("");
if (sar==sval)
{
alert("found!");
break;
}
}
Why don't you use javascript array functions?
function filterArrayByValues(array, values) {
return array.filter(function (arrayItem) {
return values.some(function (value) {
return value === arrayItem;
});
});
}
Or if your array is more complicated, and you want compare only one property but as result return whole object:
function filterArrayByValues(array, values, propertyName) {
return array.filter(function (arrayItem) {
return values.some(function (value) {
return value === arrayItem[propertyName];
});
});
}
More about used functions: filter() and some()
You can use Array.prototype.some(), Array.prototype.every() to check each element of each array.
var ar = [
[2, 6, 89, 45],
[3, 566, 23, 79],
[434, 677, 9, 23]
];
var val = [3, 566, 23, 79];
var bool = ar.some(function(arr) {
return arr.every(function(prop, index) {
return val[index] === prop
})
});
console.log(bool);
I guess there is no such JS functionality available. but you can create one
function arrEquals( one, two )
{
if( one.length != two.length )
{
return false;
}
for( i = 0; i < one.length; i++ )
{
if( one[i] != two[i] )
{
return false;
}
}
return true;
}
The problem with this is that of object/array equality in Javascript. Essentially, the problem is that two arrays are not equal, even if they have the same values. You need to loop through the array and compare the members to your search key (val), but you'll need a way of accurately comparing arrays.
The easiest way round this is to use a library that allows array/object comparison. underscore.js has a very attractive method to do this:
for (var i = 0; i < ar.length; i++) {
if (_.isEqual(ar[i], val)) {
// value is present
}
}
If you don't want to use another library (though I would urge you to -- or at least borrow the message from the Underscore source), you could do this with JSON.stringify...
var valJSON = JSON.stringify(val);
for (var i = 0; i < ar.length; i++) {
if (valJSON === JSON.stringify(ar[i]) {
// value is present
}
}
This will almost certainly be significantly slower, however.
You can use toString convertion to compare elements
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var val = [3,566,23,79];
s = !ar.every(a => (a.toString() != val.toString()));
console.log(s) // true
Use this instead
if (ar.join(".").indexOf(val) > -1) {
return true;
} else {
return false;
}
Use lodash isEqual
const isValIncludedInAr = ar.some(element => isEqual(element, val))
const arrayOne = [2,6,89,45];
const arrayTwo = [3,566,23,79];
const arrayThree = [434,677,9,23];
const data = new Set([arrayOne, arrayTwo, arrayThree]);
// Check array if exist
console.log( data.has(arrayTwo) ); // It will return true.
// If you want to make a set into array it's simple
const arrayData = [...data];
console.log(arrayData); // It will return [[2,6,89,45], [3,566,23,79], [434,677,9,23]]
I need to know if one or more duplicates exist in a list. Is there a way to do this without travelling through the list more than once?
Thanks guys for the suggestions. I ended up using this because it was the simplest to implement:
var names = [];
var namesLen = names.length;
for (i=0; i<namesLen; i++) {
for (x=0; x<namesLen; x++) {
if (names[i] === names[x] && (i !== x)) {alert('dupe')}
}
}
Well the usual way to do that would be to put each item in a hashmap dictionary and you could check if it was already inserted. If your list is of objects they you would have to create your own hash function on the object as you would know what makes each one unique. Check out the answer to this question.
JavaScript Hashmap Equivalent
This method uses an object as a lookup table to keep track of how many and which dups were found. It then returns an object with each dup and the dup count.
function findDups(list) {
var uniques = {}, val;
var dups = {};
for (var i = 0, len = list.length; i < len; i++) {
val = list[i];
if (val in uniques) {
uniques[val]++;
dups[val] = uniques[val];
} else {
uniques[val] = 1;
}
}
return(dups);
}
var data = [1,2,3,4,5,2,3,2,6,8,9,9];
findDups(data); // returns {2: 3, 3: 2, 9: 2}
var data2 = [1,2,3,4,5,6,7,8,9];
findDups(data2); // returns {}
var data3 = [1,1,1,1,1,2,3,4];
findDups(data3); // returns {1: 5}
Since we now have ES6 available with the built-in Map object, here's a version of findDups() that uses the Map object:
function findDups(list) {
const uniques = new Set(); // set of items found
const dups = new Map(); // count of items that have dups
for (let val of list) {
if (uniques.has(val)) {
let cnt = dups.get(val) || 1;
dups.set(val, ++cnt);
} else {
uniques.add(val);
}
}
return dups;
}
var data = [1,2,3,4,5,2,3,2,6,8,9,9];
log(findDups(data)); // returns {2 => 3, 3 => 2, 9 => 2}
var data2 = [1,2,3,4,5,6,7,8,9];
log(findDups(data2)); // returns empty map
var data3 = [1,1,1,1,1,2,3,4];
log(findDups(data3)); // returns {1 => 5}
// display resulting Map object (only used for debugging display in snippet)
function log(map) {
let output = [];
for (let [key, value] of map) {
output.push(key + " => " + value);
}
let div = document.createElement("div");
div.innerHTML = "{" + output.join(", ") + "}";
document.body.appendChild(div);
}
If your strings are in an array (A) you can use A.some-
it will return true and quit as soon as it finds a duplicate,
or return false if it has checked them all without any duplicates.
has_duplicates= A.some(function(itm){
return A.indexOf(itm)===A.lastIndexOf(itm);
});
If your list was just words or phrases, you could put them into an associative array.
var list=new Array("foo", "bar", "foobar", "foo", "bar");
var newlist= new Array();
for(i in list){
if(newlist[list[i]])
newlist[list[i]]++;
else
newlist[list[i]]=1;
}
Your final array should look like this:
"foo"=>2, "bar"=>2, "foobar"=>1
Let's say we have the following js array
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var val = [3,566,23,79];
Is there a js builtin function or jQuery one with which you can search the array ar for val?
Thanks
***UPDATE*************
Taking fusion's response I created this prototype
Array.prototype.containsArray = function(val) {
var hash = {};
for(var i=0; i<this.length; i++) {
hash[this[i]] = i;
}
return hash.hasOwnProperty(val);
}
you could create a hash.
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var hash = {};
for(var i = 0 ; i < ar.length; i += 1) {
hash[ar[i]] = i;
}
var val = [434,677,9,23];
if(hash.hasOwnProperty(val)) {
document.write(hash[val]);
}
You can also use a trick with JSON serializing. It is short and simple, but kind of hacky.
It works, because "[0,1]" === "[0,1]".
Here is the working demo snippet:
Array.prototype.indexOfForArrays = function(search)
{
var searchJson = JSON.stringify(search); // "[3,566,23,79]"
var arrJson = this.map(JSON.stringify); // ["[2,6,89,45]", "[3,566,23,79]", "[434,677,9,23]"]
return arrJson.indexOf(searchJson);
};
var arr = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
document.body.innerText = arr.indexOfForArrays([3,566,23,79]);
function indexOfArray(val, array) {
var hash = {};
for (var i = 0; i < array.length; i++) {
hash[array[i]] = i;
}
return (hash.hasOwnProperty(val)) ? hash[val] : -1;
};
I consider this more useful for than containsArray(). It solves the same problem (using a hash table) but returns the index (rather than only boolean true/false).
Can you try this?
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var val = [3,566,23,79];
var sval = val.join("");
for(var i in ar)
{
var sar = ar[i].join("");
if (sar==sval)
{
alert("found!");
break;
}
}
Why don't you use javascript array functions?
function filterArrayByValues(array, values) {
return array.filter(function (arrayItem) {
return values.some(function (value) {
return value === arrayItem;
});
});
}
Or if your array is more complicated, and you want compare only one property but as result return whole object:
function filterArrayByValues(array, values, propertyName) {
return array.filter(function (arrayItem) {
return values.some(function (value) {
return value === arrayItem[propertyName];
});
});
}
More about used functions: filter() and some()
You can use Array.prototype.some(), Array.prototype.every() to check each element of each array.
var ar = [
[2, 6, 89, 45],
[3, 566, 23, 79],
[434, 677, 9, 23]
];
var val = [3, 566, 23, 79];
var bool = ar.some(function(arr) {
return arr.every(function(prop, index) {
return val[index] === prop
})
});
console.log(bool);
I guess there is no such JS functionality available. but you can create one
function arrEquals( one, two )
{
if( one.length != two.length )
{
return false;
}
for( i = 0; i < one.length; i++ )
{
if( one[i] != two[i] )
{
return false;
}
}
return true;
}
The problem with this is that of object/array equality in Javascript. Essentially, the problem is that two arrays are not equal, even if they have the same values. You need to loop through the array and compare the members to your search key (val), but you'll need a way of accurately comparing arrays.
The easiest way round this is to use a library that allows array/object comparison. underscore.js has a very attractive method to do this:
for (var i = 0; i < ar.length; i++) {
if (_.isEqual(ar[i], val)) {
// value is present
}
}
If you don't want to use another library (though I would urge you to -- or at least borrow the message from the Underscore source), you could do this with JSON.stringify...
var valJSON = JSON.stringify(val);
for (var i = 0; i < ar.length; i++) {
if (valJSON === JSON.stringify(ar[i]) {
// value is present
}
}
This will almost certainly be significantly slower, however.
You can use toString convertion to compare elements
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var val = [3,566,23,79];
s = !ar.every(a => (a.toString() != val.toString()));
console.log(s) // true
Use this instead
if (ar.join(".").indexOf(val) > -1) {
return true;
} else {
return false;
}
Use lodash isEqual
const isValIncludedInAr = ar.some(element => isEqual(element, val))
const arrayOne = [2,6,89,45];
const arrayTwo = [3,566,23,79];
const arrayThree = [434,677,9,23];
const data = new Set([arrayOne, arrayTwo, arrayThree]);
// Check array if exist
console.log( data.has(arrayTwo) ); // It will return true.
// If you want to make a set into array it's simple
const arrayData = [...data];
console.log(arrayData); // It will return [[2,6,89,45], [3,566,23,79], [434,677,9,23]]