Javascript Array Equality Fails [duplicate] - javascript

This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 6 years ago.
I've got two lists. When I run array1 == array2, the console prints false. If I iterate through them and check equality for each item, it prints true every time. What's wrong?
for (var i=0; i<array1.length; i++) {
console.log(array1[i] == array2[i]);
}
From the Safari console:
All my google searches turned up things about array diffs and checking equality of unordered arrays. I thought there must be an easier way to solve the problem of two lists in the same order, and I couldn't find that online.

use array1[i].equals(array2[i]) Like it was stated in the comments you are not comparing the contents with the ==.

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?

What does `empty` mean in a JS array? [duplicate]

This question already has answers here:
What is "undefined x 1" in JavaScript?
(5 answers)
What's the difference between empty items in a JavaScript array and undefined? [duplicate]
(2 answers)
Closed 3 years ago.
Can anyone help me understand what an empty means in a JS array?
I just noticed an array in chrome devtools with an empty value. I created the one below, and by putting two commas together I can produce an empty (see below). Granted, I'm relatively new to JS, but since empty isn't a JS primitive I would have expected either:
a) a null or undefine3d value for a[3]
b) a.length to be 4
What does empty mean?
Array literals can include elisions, e.g.
[0,1,,3];
The two commas together mean "there is no element at index 2". Many stringified versions will show undefined at index 2, however that is misleading as there is no element at all at that position.
E.g.
let arr = [0,1,,3];
arr.forEach((v, i) => console.log(`index ${i} has value ${v}`));
console.log('stringified: ' + arr);
console.log('SO console:', arr);
console.log('JSON: ' + JSON.stringify(arr));
An alternative is to show "empty", which (IMHO) isn't really suitable either, it should be shown as in the literal (i.e. as for "stringified").

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

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

What means an empty element in an array and why it has taken into account in the length if theoretically it does not exist [duplicate]

This question already has answers here:
Memory allocation of a Javascript array?
(3 answers)
Closed 4 years ago.
I add a element to the array in a higher position than its length
I wonder if is there a way to access or delete this empty elements, I think it can waste memory
When doing this, you create a "sparse array". The items in between the non-null entries contain undefined. As such, the memory footprint is negligible. You cannot delete them. If you don't like this behavior, just don't create sparse arrays.
For filtering non sparse/dense elements, you could use a callback which returns for every element true.
Maybe this link helps a bit to understand the mechanic of a sparse array: JavaScript: sparse arrays vs. dense arrays.
let array = new Array(99999),
nonsparse;
array[30] = undefined;
nonsparse = array.filter(_ => true);
console.log(nonsparse);
console.log(nonsparse.length);

Array.indexOf Not working [duplicate]

This question already has answers here:
Why Array.indexOf doesn't find identical looking objects
(8 answers)
Closed 7 years ago.
I have an angularJS/Typescript application where I am trying to check if an object is already in a current list of objects
if (this.selectedFormatData.indexOf(item) === -1) {
//doesn't exist so add
this.selectedFormatData.push(item);
} else {
this.selectedFormatData.splice(this.selectedFormatData.indexOf(item), 1);
}
I have used this code before and it worked but isn't in this instance. Console output suggests it should work?
Any ideas?
Update: yeah correct looks like a duplicate sorry. I had a previous bit of code where i thought it worked because it was returning 0 instead of -1. Not sure why it would return 0 though
As the comments state, indexOf() is not meant to compare objects. This has been answered before here: Why Array.indexOf doesn't find identical looking objects.

Categories

Resources