Javascript conditions in an object - javascript

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);

Related

javascript - filter array of strings based on seperated ending

I have an array of strings like this:
const strings = [
"author:app:1.0.0",
"author:app:1.0.1",
"author:app2:1.0.0",
"author:app2:1.0.2",
"author:app3:1.0.1"
];
And I want to filter them so that only the ones that have the latest versions for the given "author:name" are left, thus removing ones that are not the latest (i.e. the "1.0.1" ones).
My expected result is this:
const filteredStrings = [
"author:app:1.0.1",
"author:app2:1.0.2",
"author:app3:1.0.1"
];
Any way to do this simply?
You can do it with two loops first one find new ones second one check which is bigger
const strings = [
"author:app:1.0.0",
"author:app:1.0.1",
"author:app2:1.0.0",
"author:app2:1.0.2",
"author:app3:1.0.1"
];
filteredones = [];
strings.forEach(element => {
var arr = element.split(":");
var isnew = true;
var found = filteredones.find(function(element2) {
var x = element2.split(":");
return x[1] == arr[1] && x[0] == arr[0]
});
if (found == undefined) {
filteredones.push(element);
}
});
for (var i = 0; i < filteredones.length; i++) {
element = filteredones[i];
var arr = element.split(":");
var isnew = true;
var found = strings.find(function(element2) {
var x = element2.split(":");
return x[1] == arr[1] && x[0] == arr[0] && x[2] > arr[2]
});
if (found != undefined) {
filteredones[i] = found;
}
};
console.log(filteredones);
you can check the value in the last index of the string in each of the elements of the array and if they qualify as a latest one put it to a new array.
You can use an object to store the key/version pairs, and convert to appropriate output on the end. The version comparison can be any of those found here: How to compare software version number using js? (only number)
result = {};
for (var s of input) {
// parts = ["author", "appname", "version"]
var parts = s.split(":");
var i = parts[0] + ":" + parts[1];
if (!result[i] || compareVersion(parts[2], result[i]))
// If not present or version is greater
result[i] = parts[2]; // Add to result
}
result = Object.keys(result).map(k => k + ":" + result[k])
Working demo: https://codepen.io/bortao/pen/LYVmagK
Build an object with keys as app name.
getValue method is calculate the version value so that to compare.
Update object value, when you see the version is recent (value is big).
const strings = [
"author:app:1.0.0",
"author:app:1.0.1",
"author:app2:1.0.0",
"author:app2:1.0.2",
"author:app3:1.0.1"
];
const filter = data => {
const res = {};
const getValue = item =>
item
.split(":")[2]
.split(".")
.reduceRight((acc, curr, i) => acc + curr * Math.pow(10, i), 0);
data.forEach(item => {
const app = item
.split(":")
.slice(0, 2)
.join(":");
if (!res[app] || (app in res && getValue(item) > getValue(res[app]))) {
res[app] = item;
}
});
return Object.values(res);
};
console.log(filter(strings));

Push different object in an array with a for loop

I have an element structured like this:
Element ->
[{values: arrayOfObject, key:'name1'}, ... ,{values: arrayOfObjectN, key:'nameN'}]
arrayDiObject -> [Object1, Object2, ... , ObjectN] //N = number of lines in my CSV
Object1 -> {x,y}
I have to take data from a big string:
cityX#substanceX#cityY#substanceY#
I thought to make it this way, but it seems like it pushes always in the same array of objects. If I put oggetto = {values: arrayDateValue, key: key}; inside the d3.csv function, instead if I put outside the function it add me only empty objects.
Here is my code:
var final = new Array();
var oggetto;
var key;
function creaDati() {
var newdate;
var arrayDateValue = new Array();
var selString = aggiungiElemento().split("#");
//selString is an array with selString[0]: city, selString[1]: substance and so on..
var citySelected = "";
var substanceSelected = "";
for (var i = 0; i < selString.length - 1; i++) {
if (i % 2 === 0) {
citySelected = selString[i];
} else if (i % 2 !== 0) {
substanceSelected = selString[i];
key = citySelected + "#" + substanceSelected;
d3.csv("/CSV/" + citySelected + ".csv", function(error, dataset) {
dataset.forEach(function(d) {
arrayDateValue.push({
x: d.newdate,
y: d[substanceSelected]
});
});
});
oggetto = {
values: arrayDateValue,
key: key
};
arrayDateValue = [];
final.push(oggetto);
}
}
}
Any idea ?
First you should make the if statement for the city and then for the key, which you seem to be doing wrong since you want the pair indexes to be the keys and the not pair to be the city, and you are doing the opposite. And then you need to have the d3.csv and push the objects outside of the if statement, otherwise in your case you are just adding elements with citySelected="".
Try something like :
for(var i = 0; i < selString.length -1; i+=2){
cittySelected = selString[i];
substanceSelected = selString[i+1];
key = citySelected + "#" + substanceSelected;
d3.csv("/CSV/"+citySelected+".csv", function(error, dataset){
dataset.forEach(function(d){
arrayDateValue.push({x: d.newdate, y: d[substanceSelected]});
});
});
oggetto = {values: arrayDateValue, key: key};
arrayDateValue = [];
final.push(oggetto);
}
It's is not the best way to do it, but it is clearer that what you are following, i think.
In the if(i % 2 == 0) { citySelected = ... } and else if(i % 2 !== 0) { substanceSelected = ... } citySelected and substanceSelected will never come together.
The values should be in one statement:
if(...) { citySelected = ...; substanceSelected = ...; }
The string can be splitted into pairs
city1#substance1, city2#substance2, ...
with a regex (\w{1,}#\w{1,}#).
Empty the arrayDateValue after the if-statement.
Hint:
var str = "cityX#substanceX#cityY#substanceY#";
function createArr(str) {
var obj = {};
var result = [];
var key = "";
// '', cityX#substanceX, '', cityYsubstanceY
var pairs = str.split(/(\w{1,}#\w{1,}#)/g);
for (var i = 0; i < pairs.length; i++) {
if(i % 2 !== 0) {
key = pairs[i];
// d3 stuff to create values
obj = {
// Values created with d3 placeholder
values: [{x: "x", y: "y"}],
// Pair
key: key
};
result.push(obj);
}
// Here should be values = [];
}
return result;
}
var r = createArr(str);
console.log(r);
May be you can do like this;
var str = "cityX#substanceX#cityY#substanceY",
arr = str.split("#").reduce((p,c,i,a) => i%2 === 0 ? p.concat({city:c, key:a[i+1]}) : p,[]);
console.log(JSON.stringify(arr));
RESOLVED-
The problem is about d3.csv which is a asynchronous function, it add in the array when it finish to run all the other code.
I make an XMLHttpRequest for each csv file and it works.
Hope it helps.

Match two multidimensional array in Javascript

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]);
});

Multidimensional Array - Test if all values are equivilant in nested array

So, I have an array that looks like this:
[ ["","",""], ["","",""], ["","",""] ]
How would I test it in javascript to see if, perhaps, the 1st index was filled with X's?
EX: [ ["X","X","X"], ["","",""], ["","",""] ]
I keep thinking I should do something like this, but it feels like there would be a quicker way...
var counter = 0,
win,
b = [ ["X","X","X"], ["","",""], ["","",""] ],
num = b[0].length;
for(var i=0; i<num; i++){
if(b[0][i]==="X"){ counter++; }
}
if(num===counter){ win=true; }
var win = b[0].join('') === 'XXX';
Use Array.prototype.every. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
function isAnX(c) { return c === 'X'; }
var win = b[0].every(isAnX);
win = true;
for (var i = 0; i < num; i++) {
if (b[0][i] != "X") {
win = false;
break;
}
}
Here's how to test if an array contains identical elements:
allTheSame = someArray.every(function(x, _, ary) { return x == ary[0] })
see every
or, for pre-ES5 engines:
allTheSame = function(ary) {
for(var i = 1; i < ary.length; i++)
if(ary[i] != ary[0]) return false;
return true;
}
use Array.prototype.reduce
var win=b[0].reduce(function (v, c) { return v && (c=="X") }, true);
Another one, just to give one more option:
var win = new RegExp("^X{"+b[0].length+"}$").test(b[0].join(''));
Cheers
Similar to other answers, but with something of a twist:
var all = function(val, arr) {
var fn = function(arr) {return arr.every(function(item) {return item === val;});};
return arguments.length > 1 ? fn(arr) : fn;
};
var win = all('X', b[0]); //=> true
// or
var allXs = all('X');
var win = allXs(b[0]); //=> true
Or if you just want to know if they're all the same:
var allAlike = function(arr) {
return (arr.length == 0) || all(arr[0], arr);
}
var win = allAlike(b[0]);
This would be easier if you had an appropriate curry-like function available.
Hahaha, this is cool:
var win = Array(b[0].length+1).join('X') == b[0].join('')
Cheers!

javascript search array of arrays

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]]

Categories

Resources