Can Anyone Explain The Following Javascript Code For Unique Value How Is It Internally Compared With Each Other
Solution 1:
return arr.indexOf(value) === arr.lastIndexOf(value);
You have an array. Every element in the array has an index. .indexOf()
will give you that index. So if an element is unique, the first index it appears at is the same as the last index. If the element would not be unique, the lastIndex will be higher than the (first)Index.
})[0] || -1; // how this works======================= B
This will just return the first element of the filtered array. And if the array is empty or if the first element is falsey ( 0, null, undefined, ... ), return -1. Its equivalent to if ( array.length && array[ 0 ] ) { return array[ 0 ]; } else return -1
.
So the function in it's entirity will just return you either the first unique element inside the array, or -1 if all elements have at least one duplicate.
OK, Let's try again:
1) The function wants to return the first unique element that appears in an array. So if we have an array [ 1, 1, 3, 7, 10, 10 ]
, the result should be 3, since 1 appears two times in the arrray.
2) So the first step is making sure the array only contains unique elements. We do this by filtering out all the non-unique elements in the array.
To do so, we use Array.filter()
, the basic array method to filter elements out of an array. This filter()
method expects us to provide a function that will return true or false. The method will then loop over the array, applying the function on each element. All the elements the function returns true for, will stay in the results array. All the elements we return false for, will get removed from the results.
For example: [ 1, 1, 3, 7, 10, 10 ].filter(( element ) => element > 5);
In this example we return true if an element is bigger than 5, and false if its smaller than 5. So our result will be [ 7, 10, 10 ]
3) The function we want to actually use here, is to return true for elements that are unique and false for elements that aren't. An unique element appears only once inside an array. So we can leverage array.indexOf()
and array.lastIndexOf()
. The former will return the first index an element appears at. The second the last index.
Example: let's assume our array is [ 1, 1, 1, 9, 7, 10, 7, 21 ]
and that the element we're checking is the value 1.
The .indexOf( 1 ) is 0
, since the first appearance of the value 1 inside the array, is the first index, since our array starts with the value 1.
The .lastIndexOf( 1 ) is 2
, since the 3rd element of the array is also 1.
Compare this to the value 9.
The .indexOf( 9 ) is 3
, since it's the 4th element of the array.
The .lastIndexOf( 9 ) is also 3
, since there's only one 9 inside the array. So both indexOf and lastIndexOf find that same index.
4) Once we have the index and lastIndex of an element , we then compare them:
arr.indexOf(value) === arr.lastIndexOf(value)
.
So let's continue with the previous example: [ 1, 1, 1, 9, 7, 10, 7, 21 ]
.
For the value 1, the index was 0 and the lastIndex was 2. Compared to eachother, this is false, since ( 1 === 2 ) = false;
. So we return false for all the values 1 inside the array and hence, they get filtered away in the result.
For the value 9, the index was 3 and the lastIndex as well. So our comparison becomes ( 3 === 3 ) = true;
. So we return true from inside the filter function and hence, 9 gets to stay inside the results.
5) This logic gets used on all the elements in the source array. All the elements where the index isn't the same as their lastIndex, get filtered away. All the elements where both indices are the same, are unique since they only appear once, and so they can stay.
Solution 2:
Info: Example code was changed a little bit to be more readable, although it still defines exactly the same functionality.
A:
var uniqueArray = arr.filter(function(value) {
return arr.indexOf(value) === arr.lastIndexOf(value);
})
The
indexOf()
method returns the first index at which a given element can be found.The
lastIndexOf()
method returns the last index at which a given element can be found in the array.The
===
means it compares the two indices (first and last). If they are the same (true), we know that the element is unique - it will be kept in thearr.filter
method call.
B:
return uniqueArray[0] || -1;
- The
[0] || -1
is expected to return either the first element of the new unique array or if there are no elements in the unique array, it will return-1
as a fallback.
Attention:
[0] || -1
is very dangerous! It will also return-1
when the first element exists but is falsy. e.g.0
or""
will also return a-1
even though they exist and could be returned. A better approach would be to check if elements exist in the array first:if(array.length > 0)
and only return-1
if none exist.
Sources
Solution 3:
Okay, it's a bit inefficient, but it returns the first unique value in an array - or if there is no unique value -1
.
functiongetUniqueFromArray(arr){
return arr.filter(function(value){
return arr.indexOf(value) === arr.lastIndexOf(value); // how this works ===============A
})[0] || -1; // how this works======================= B
}
For each value in the array, it checks whether it is unique by finding the index of the value itself and the lastIndex of the value. With [1,2,3,1]
you would have 0 === 3 //false
.
If that condititon is true, the value remains in the array. Of the returned array, the first value is picked ([0]
). The ||
mean that if the first value is falsy (null
, undefined
or in any other way !value
would be true) it returns -1
.
There is probably a bug in that code (aside the inefficiency) for the value 0
. If 0
is the first unique value in the array, -1
would be returned, as !0 === true //true
Solution 4:
A - means return true or false - whether it returns true or false will be determined by whether the comparison arr.indexOf(value) === arr.lastIndexOf(value)
returns true or false. It's just a compression of something like
var result = (arr.indexOf(value) === arr.lastIndexOf(value));
return result;
or even more simplistically / redundantly
if (arr.indexOf(value) === arr.lastIndexOf(value)) { returntrue; }
else { returnfalse; }
(If you want to know what the Array.IndexOf method does, you can already look it up.)
B - [0]
means to select the first element returned by the filter()
method (since that method returns an array), and || -1
means "or -1"...i.e. it's a caveat that if that first element isn't defined, then just return -1 instead. It's like setting a default value. However it's not very reliable - if the first element returned is false-y (e.g. an integer 0
, or an empty string (see here for details)) then this side of the expression will be false and the the function will incorrectly return -1 instead. Also there's no way to tell if -1 was in fact the value of the first element returned, or if it indicates no results. It would probably have been better to have it return null
or something.
Post a Comment for "Can Anyone Explain The Following Javascript Code For Unique Value How Is It Internally Compared With Each Other"