comparing 2 arrays with _.difference - javascript

Im using lodash with some calculations, but there is a function that isnt working has i expected, im using for example 'difference'.
His usage is:
_.difference([2, 1], [2, 3]);
output: [1]
But when i apply to my arrays:
_.difference([5111471, 5111513], [5111471,5111505,5111513]);
output:[]
Instead of giving me [5111505], is giving me a empty array.

_.difference returns elements of the first array not present in the second one. There are no such elements in your example, hence the empty result. If you want a symmetric difference (that is, elements that are present in the first array or the second, but not in both), you can do something like
diff = _.union(_.difference(a, b), _.difference(b, a))

_.difference doesn't actually return the difference between two arrays, but instead returns the first array minus the second. So to return [5111505] you need to do:
_.difference([5111471,5111505,5111513],[5111471, 5111513]);
See documentation for more info:
https://lodash.com/docs/4.15.0#difference

Related

JS .reverse array using .sort - a trick which doesn't seem to work?

I want to get the same results which method Array.prototype.reverse() gives. I found this trick using .sort(), but it doesn't work in my Chrome console.
Why doesn't this code reverse an array?
const trickReverse = arr => arr.sort(x => 1);
console.log(trickReverse([1, 2, 3])); -> [1, 2, 3]
Explanation: The .sort method accepts a function that normally takes 2 arguments, in this case we don't care about them and use 'x'. That function compares the 2 elements and returns a negative number if they are in correct order, zero if they are equal, and a positive number if they are in incorrect order. Usually you give it a function that actually does something useful. In this solution we've exploited it to always return a positive number (1). So that means it will think every 2 elements that are compared are in the wrong order, hence reversing the entire array.
The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
// Functionless sort()
// Arrow function sort((a, b) => { /* ... */ } )
// a is the first element for comparison and b is the second element for
// comparison.
Parameters in the sort() method specify a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.
Note that the array is sorted in place, and no copy is made.
The answer you need might be the answer given below or nearly corresponds to it.
The sort method can be conveniently used with function expressions:
const numbers = [1, 2, 3];
numbers.sort(function(a, b) {
return b - a;
});
console.log(numbers);
// [3, 2, 1]
This perfectly reverses an array with any count of numbers you have.
For reference, you can read sort() method documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#:~:text=The%20sort%20method%20can%20be%20conveniently%20used%20with%20function%20expressions%3A
The comparison function will swap the elements if the comparison function returns negative .
so, just change the `
const trickReverse = arr => arr.sort(e => -1);
console.log(trickReverse([1, 2, 3])); -> [ 3,2,1]
`
This will do the trick
For
reference

Javascript. help understanding how the comparison function when sorting numbers in an array works

Okay, so i understand how to sort numbers from big to small or small to big. what I don't understand is how it actually is done by javascript. can somebody walk me through, step by step how javascript is sorting the following array? I know how to use it, I need to understand it.
var arr = [3, 2, 4, 5, 1]
function sorter(a, b) {
return a - b;
}
arr.sort(sorter)
can you show me which number is for a, and which is for b, and how does it iterate through the rest of the array. For instance, 3 - 2 is 1, so it would switch 2 to an index lower than 3, how does this continue for this entire array? I want to understand why this works, not just use it blindly. Thanks!!
can you show me which number is for a, and which is for b, and how does it iterate through the rest of the array.
it doesn't matter; and it is not specified.
Browsers can implement whatever sorting algorithm they want. All that's defined is that they call the function with two different entries in the Array (different in terms of index, not as different values) and your function should return
0 if these values are identical in terms of order
<0 if the first argument should be before the second argument
>0 if the first argument should be after the second argument
You may want to check out some sorting algorithms

What exactly is a dense array?

The explanation for a dense array that I read from a few pages seem to be in contradiction to one another. I'd like some help understanding what it is.
While some links (search result 1, search result 2) suggest that it simply is an array where:
the elements of the array are known to be specific values; and
are assigned to the array at the time of its initialization.
The allusion there is that JavaScript arrays are dense.
It all makes sense up until here.
But this statement taken from the JavaScript Guide on the Mozilla Developer Network (MDN) says:
Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are
not guaranteed to be dense; this depends on how the programmer chooses
to use them. In general, these are convenient characteristics; but if
these features are not desirable for your particular use, you might
consider using typed arrays.
And this has confused me now. My question is:
What does the statement on the MDN page mean when it says JavaScript arrays are not guaranteed to be dense? If it means that the following is not a dense array because one or more of its elements are undefined at the time of initialization, then why do the links I listed above seem to indicate that JavaScript arrays are indeed dense?
var array = new Array(1, , 3, ); // [1, undefined, 3, undefined]
"Dense" is in opposition to "sparse", and generally is used when talking about storage. For example, this array is dense:
a = [undefined, undefined, 2]
It can be stored in memory exactly like that: a sequence of three locations, the first two being undefined, the third being 2.
This array is sparse:
a = []
a[100000000] = 100000000
It is not stored in memory as a sequence of 100000001 locations, as it would be horribly inefficient. It is definitely not 100000000 places of undefined followed by 100000000. Rather, it just says 100000000th one is 100000000, and there is no space allocated to the first 100000000 elements.
(Actually, try to do this with 2 instead of 100000000, and you'll notice a curious thing: Chrome will display the dense array as [undefined, undefined, 2], but the sparse one as [undefined × 2, 2].)
Those articles say you can create an array being dense. This means that, at the time of creation, such arrays are dense, since in arrays like:
var a = new Array("foo", "bar", "baz");
var b = [2, 3, 5];
every element is set: from 0 to length-1, there is no undefined value. Or better said: every position from 0 to length-1 was assigned a value (even if the value is, actually, undefined).
However, you can make those arrays not dense anymore, by doing something like this:
a[20] = "bat";
That array, which was dense, is not dense anymore since the elements 0 1 2 and 20 (unlike elements in 3 to 19) are set to a value (this array has 4 elements, not 21).

Overwrite the this value in array.prototype

I've found that the native js sort function screws up from time to time so I wanted to implement my own. Lets say i have the following :
Array.prototype.customSort = function(sortFunction, updated) {...}
var array = [5, 2, 3, 6]
array.customSort(function(a,b) {return a - b})
console.log(array)
Array should be [2, 3, 5, 6]
Updated is the array that has been sorted.
No matter what I return in customSort, the order of array is still in the original order. How do I overwrite the 'this' value / get it to point to the array with the correct order?
If you consider the actual code you gave above, you have to make sure that your customSort function updates this.
One case is that customSort only uses this as "read-only" input, that is - only puts the sorted array in updated, rather than changing this.
In such case, considering the code above (which you might have performed tests with), no updated parameter is sent to the function, to receive the sorted values.
Another case is that customSort returns the sorted array, in which case you have to collect it:
array = array.customSort(function(a,b) {return a - b});
console.log(array);
I just ended up iterating over the updated array and replacing each value in this with the value in updated. In code, that looks like...
function customSort(cb) {
...//updated is the sorted array that has been built
var that = this;
_.each(updated, function (ele, index) {
that[index] = ele;
})
}
I wanted the function to operate in the exact same way the native array.sort function does - it overwrites the array provided instead of returning a new, sorted array.
I find it odd that this works... you cannot overwrite the entire this value in one clean sweep but you can in steps. I couldn't do this for in the customSort function :
this = updated;

How to find index of object in array without iterating in javascript

Lets have an sample array like [1,2,3,4,5,6,7,8,9,10,12,0, 1, 2, 3,4 ]
I want to find the first occurrence of ' 0 ' in this array, but without iterating the same.
all the functions 'like', 'map', 'grep', 'filter', 'some','for each' everything iterating every element in the array to find the same. Considering big data array's its very much bottleneck considering performance.
I have tried all the above methods.
Anybody has any idea about this?. Thanks for your time.
How to find index of object in array without iterating in javascript
This is impossible. If you have a generic list of values, you have to look at each element until you find the one you are looking for.
If you want O(1) access then you need to use a different data structure.
If the elements of the array is a number or string, you can just use indexOf()
indexOf() compares searchElement (first parameter) to elements of the Array using strict
equality (the same method used by the ===, or triple-equals,
operator).
var list = [1,2,3,4,5,6,7,8,9,10,12,0, 1, 2, 3,4 ];
var firstOccurence = list.indexOf(0);

Categories