How to determine if an array includes another array in JS? [duplicate] - javascript

This question already has answers here:
Why Array.indexOf doesn't find identical looking objects
(8 answers)
Closed 3 years ago.
I'm wondering what the best way to determine the membership of one array in another array in JS.
Here's an example
let a = [];
a.push([1,2]);
a.includes([1,2]) <- evaluates to false
a.indexOf([1,2]) <- evaluates to -1
What's the deal here? Any efficient work around?

At the moment, your search array doesn't actually equal the array within your a array as they have 2 different references in memory. However, you could convert your arrays to strings, such that your search can equal another string array within your array.
To do this you could convert your inner arrays to string using .map(JSON.stringify) and then search for the string version of your array using .includes(JSON.stringify(search_arrr)).
See example below:
let a = [];
let search = [1, 2];
a.push([1,2]);
a = a.map(JSON.stringify)
console.log(a.includes(JSON.stringify(search)));

Related

The fastest and most efficient way to get repeated numbers in a nested array [duplicate]

This question already has answers here:
How to flatten nested array in javascript? [duplicate]
(27 answers)
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 5 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I know how to do this combining a lot of if...else statements but I need a faster and more efficient way.
I need a function that will run through a nested array and return the numbers that occur more than once in the nested array.
this doesn't work with nested arrays and even if you use flat(), the code still breaks when the duplicates in the array are more than 2
For example-
Lets call the name of the function deepSort(nestedArray)
where nestedArray is the nested array parameter
deepSort([[1,3,4,5], [4,7,9,1,3], [2,3,5], [1,2,3,4]]) //Returns 1,2,3,4,5
deepSort([[1,2,3], [4,5], [6,7,8], [2,9,0]]) //Returns 2
deepSort([[2,7,9], [4,3], [9,6,5], [1,4,3]]) //Returns 3,4,9
What I tried
function deepSort(nestedArray) {
const flatArr = nestedArray.flat().sort();
let results = []
for (let i = 0; i < flatArr.length - 1; i++) {
if (flatArr[i + 1] ==flatArr[i]) {
results.push(flatArr[i]);
}
}
return (results.filter((item,index) => results.indexOf(item) === index)).join()
}
Can this be optimized any more for speed and efficiency when handling larger values of data?

push value in map of arrays at a specific postition [duplicate]

This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 5 years ago.
I am creating a map of array using this:
var m = new Map(Array(40).fill(new Array()).entries());
Now, I want to push values in those array. But when I do this:
m.get(1).push(10)
The value 10 gets pushed into all the arrays instead of the one at 1st position.
You could take another pattern to build independent arrays.
var m = new Map(Array.from({ length: 40 }, _=> []).entries());
m.get(1).push(10);
console.log([...m]);
fill gets single array an uses it to fill all rows of the given array, it doesn't create a new array for each row. This means that your single array reference is shared between all rows. Because array is a reference type, you use the single reference to manipulate it, so the actual object is changed. You can check this by comparing the references of each row.
const arr = new Array(2).fill(new Array());
console.log(arr[0] === arr[1]);
For creating separate arrays, you can see #Nina's answer above

Lodash / javascript : Compare two collections and return the differences [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 6 years ago.
I have two arrays of objects:
Elements of my tables are not primitive value, but complex objects.
array1 = [obj1,obj2,obj3,obj4]
array2 = [obj5,obj5,obj6,obj7]
I would like to compare two arrays and see if the elements of array2 are already present in array1 then create a new array of the difference.
Any suggestions?
var presents = _.intersectionWith(array1, array2, _.isEqual);
var dif = _.differenceWith(array1, array2, _.isEqual);
_.differenceWith is only available since 4.0.0 lodash version
ES6 This will be enough:
array2.filter(e => !array1.includes(e));
without includes
array2.filter(e=> array1.indexOf(e) < 0);
Plunker for you
_.difference gives you only the elements that are in the 1st array but not in the second one, nothing about the elements on the array 2 that are not in the array 1.
Is this what you want to achieve?

Delete random objects from array [duplicate]

This question already has answers here:
Picking 2 random elements from array
(10 answers)
Closed 7 years ago.
I have an array such as:
array=['a','b','c','d','e','f'];
I want to delete a random 2 elements. How can I do this?
To get two unique items from the array, and if you don't mind mutating the original array, you can use splice() to remove the selected item from the array so it won't be picked when you run it a second time:
var firstRandomChoice = array.splice(Math.floor(Math.random()*array.length), 1);
var secondRandomChoice = array.splice(Math.floor(Math.random()*array.length), 1);
If you use a utility library such as lodash, you may already have a function available to do this for you. For example, lodash provides sample(). So if you were using lodash, you could just do something like this to get an array of two random items:
var results = _.sample(array, 2);

Counting Object Length based on key value [duplicate]

This question already has answers here:
How can I only keep items of an array that match a certain condition?
(3 answers)
Closed 8 years ago.
I have a JS object/ associative array with some values:
var array =[
{val:1,ref:10,rule:100},
{val:1,ref:12,rule:120},
{val:2,ref:13,rule:165},
];
And I want to perform a .length, but want to be able to slice based on one of the keys (for instance val == 1). I want the length of values with val 1 rather than the length of the entire object. I have looked through the references material and could not find a satisfactory answer and I am unsure if this is feasible.
array.val==1.length = 2
Something like that...
You want to .filter the array for elements that match some predicate:
var filteredArray = array.filter(function(element) { return element.val == 1 })
filteredArray.length // = 2
filter applies the callback function to each element in the array, and the new filtered array contains all elements from original array for which the filter callback function returned true. Here, the function returns true for all elements with a val property of 1.
You need to use a .filter():
array.filter(function(v){return v.val==1}).length

Categories

Resources