This question already has answers here:
Sort array items and preserve order of same elements
(5 answers)
Closed 3 years ago.
If the two elements have the same property value on which we sort the array then how javascript order them i mean if you have this array for example :
let array = [{id:0,name:"sam",age:"20"},
{id:0,name:"john",age:"21"},
{id:1,name:"fred",age:"30"}]
let's suppose that i want to sort this array by id ascending then how can i know which one will appear first :
{id:0,name:"sam",age:"20"}
OR
{id:0,name:"john",age:"21"}
Up until now the Array.prototype.sort was not a stable sort because there was no mentioning for it in the spec so actually there was no guaranty for a stable (consistent) order.
Though recently, the spec has changed and the V8 engine implemented it as a stable sort.
I realized after answering that this is a duplicate. See my answer to the dupetarget. Briefly: As of ES2019, Array#sort is stable, so in your example "sam" will remain before "john". Prior to ES2019, that wasn't necessarily true, they could have had their order reversed.
Related
This question already has answers here:
Check if array of objects contain certain key
(6 answers)
Closed 5 months ago.
I need to find out if an array of a JS object includes an object with a specific key.
I am using,
my_array.filter((e) => Object.keys(e).includes(my_key)).length > 0
but there must be a way to do it simpler.
Any suggestions in addition to Check if array of objects contain certain key ?
Instead of .filter(…).length > 0, use .some(…).
Instead of Object.keys(…).includes(…), use … in … (or Object.hasOwn(…, …) if you need to ignore inherited properties).
So
my_array.some(e => my_key in e)
instead of filter use some, already returns true or false and it shortcircuits as soon as it finds the first
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
This question already has answers here:
Explanation of [].slice.call in javascript?
(9 answers)
Closed 1 year ago.
Bootstrap 5 Javascript examples sometimes show code like:
var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'))
Why isn't this just:
var collapseElementList = document.querySelectorAll('.collapse')
What is [].slice.call() doing exactly? I don't understand why you'd slice on an empty array, and then I have no idea what call is doing there. What would be the problem with the obvious way to do this, the second way above?
querySelectorAll returns a NodeList, which is a collection, but not an array.
[].slice.call turns an array-like collection into an array proper. It will allow you to use array methodss on it, eg:
var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'));
const textsOfCollapsedElements = collapseElementList.map(elm => elm.textContent);
Otherwise, if you don't convert it to an array first, you won't be able to use array methods on it.
It's probably most important for forEach. Newer browsers support NodeList.prototype.forEach, but it hasn't been with us that long. In contrast, Array.prototype.forEach has existed forever. So turning the collection into an array allows for forEach to be called on it, even on obsolete browsers that don't support NodeList.prototype.forEach.
It's an idiom for turning anything array-ish (in this case a DOM NodeList) into a real Array by exploiting the fact that Array::slice can work on anything that's iterable and has a .length property.
The modern idiom is Array.from(...).
This question already has answers here:
Why Doesn't Array Concatenation Work in Javascript? [closed]
(3 answers)
Closed 2 years ago.
I am getting below like values at runtime. Below is for only example. I will have same array structure at runtime. I want to merge them.
let finalSearchResult =[];
data [{"a":1000,"a":1000001,"a":10000002,"D":5000000}]
data [{"P":1000,"Q":1000001,"R":10000002,"S":5000000}]
finalSearchResult.concat(finalSearchResult,data);
but its not working. When I am printing finalSearchResult its coming as null.
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
please refer to:
Array.prototype.concat documentation
Therefore:
finalSearchResult = finalSearchResult.concat(data);
Will be the correct way to concat the arrays.
This question already has answers here:
JavaScript - examples of reduce() function
(4 answers)
Closed 3 years ago.
What are some good scenarios in which to use reduce()? I've used map() and filter() quite a bit but I don't use reduce(), mainly b/c I'm not exactly sure what the niche/benefits of the reduce() function are.
Mainly, every scenario where you have to (ha!) reduce the initial array to one single element, while the other methods might also return an array whose length could be greater than 1
This question already has answers here:
How to check if two arrays are equal with JavaScript? [duplicate]
(16 answers)
Closed 9 years ago.
For example:
var one = ['H', 'i'];
var two = ['H', 'i'];
(one == two) returns false
but
(one.join('') == two.join('')) returns true
Why is that?
There is a difference on how equality is defined for strings and arrays - strings are considered equal if their contents are identical, but arrays are considered equal only if it's the same array, and different otherwise even if their contents match.
There are a bunch of reasons why it could be the way it is, for example two reasons:
1) you often don't want array comparison to go through the whole array, because it could be huge and would take a huge time. So the default way shouldn't be dangerous.
2) you can alter array contents while still being 'the same' array; while javascript strings are immutable so any changed string is a new, different object.
When comparing objects, JS wants to see if they are the actual same object, not just an object with the same contents.
I find underscore's isEqual method useful here, but if you want to figure out how it is done library free, just glance at underscores core, which is very easy to read
http://underscorejs.org/#isEqual