How to sort object elements in javascript? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sorting a JavaScript object
Sort JavaScript object by key
I have array:
var arr = {}
arr[2323] = 1
arr[123] = 1
...
arr[n+232323] = 1
How to get all element of aobject sorted by key ( number order ? )
for ( key in arr ) {
alert(typeof(key))
}
return string type.

This is not an assosiative array, this is an object. There are no associative arrays in javascript.
Additionally, objects are not ordered. The order of keys in an object is meaningless.

Assuming there's some reason you don't use an Array in the first place, you can get an Array of the enumerable object properties, and sort that Array...
var sorted = Object.keys(my_obj)
.sort(function(a,b) {
return a - b;
});
This assumes the keys are numeric.
Then you can iterate the Array, and use each key to get the value from my_obj...
sorted.forEach(function(key) {
console.log(my_obj[key]);
});

Short answer: You can't.
Long answer: Associative Arrays in JavaScript are really JavaScript objects. When you add a new element, you're really adding a new member to the object. While most browsers will enumerate those members in the order they were added, the standard states that the order is undefined. You can't sort something that is undefined.

JavaScript objects (maps/dictionaries/associative arrays) have no order, you can't sort them. You will need to convert it to an array first. As you only need the keys of your object in your loop, the Object.keys() function (potentionally needs a shim for older browsers) is destined for the task:
var obj = {...};
var keys = Object.keys(obj).sort(function(a,b){return a-b;}); // numerically sorted
for (var i=0; i<keys.length; i++) {
alert(keys[i]);
// access the values by obj[keys[i]]
}

Related

How can I add an Object into an array nested inside an Object in Javascript? [duplicate]

What's the difference between var = [] and var = {} in JavaScript?
[] is an empty array (i.e. with zero items).
{} is an empty object (i.e. with zero key-value pairs).
Here you can find some info about your doubts: https://www.w3schools.com/js/js_datatypes.asp

Javascript associative array does not support Array.prototype.map function [duplicate]

This question already has answers here:
Length of a JavaScript associative array
(4 answers)
Closed 4 years ago.
After long times programming, I don't know why never have seen this:
var array = [];
array['one'] = 1;
console.log(array.length);
Here is a fiddle that shows array.length is zero (0):
https://jsfiddle.net/0c9v5txe/1/
Of-course, I don't need the length of array, just array.map is not working when the length is zero.
Isn't there really a way to force Javascript update the length of an associative array when adding a new item?
JavaScript doesn't have a feature called "associative arrays".
It has objects, and arrays are a type of object designed to hold numerically indexed values. (The length property on an array is calculated based on the highest numbered numerical property).
(Since arrays are a type of object, you can store arbitrary properties on them, but this is not a good practice).
If you want to store named properties, then do not use an array. Use a plain object or a Map. These serve the same purposes as associative arrays in other languages.
You can count the enumerated properties of an object by extracting them into an array and then checking its length.
var myObject = {};
myObject.one = 1;
console.log(Object.keys(myObject).length);
you need to pass index, not value
array[index] = value;
var array = [];
array[0] = "one";
console.log(array.length)

Trying to sort object turns into array object [duplicate]

This question already has answers here:
Sort JavaScript object by key
(37 answers)
Closed 4 years ago.
This how the default api returns. I want to sort them with basis of min_conversion_count properties.
After sorting the structure changes which is affecting my code. How is it possible to sort them with the property and remain the same format.
Code to sort
var rewarddata = res1.response.reward_list;
// console.log(rewarddata);
sortable_data = [];
console.log(rewarddata);
for (var idx in rewarddata)
{
sortable_data.push([idx,rewarddata[idx]]);
sortable_data.sort(function(a, b) {
return a[1].min_conversion_count - b[1].min_conversion_count;
});
console.log(sortable_data);
}
After sorting it changes like this.
You started out with an object, and you put it into an array in order to sort it; once your array is sorted, you have to turn it back into an object.
const sortedObj = sortable_data.reduce((accum, [key, value]) => {
accum[key] = value;
return accum;
}, {});
Note that property ordering is generally not something to rely on. It would be better to save an array of the sorted keys only, and then use that array instead.

javascript: not getting proper results with callback function [duplicate]

This question already has answers here:
Length of a JavaScript object
(43 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I looked at similar questions and tried Object.key(patientList).length but it returns 0. I was recommended to use callbacks and this how I am implementing it.
var data;
var patientList = {};
var parseDate = d3.time.format("%d/%m/%y").parse;
function input_Data() {
d3.json("data.php", function(error, json) {
if (error) return console.warn(error);
data = json;
console.log(data);
for(var i = 0; i < data.length; i++) {
var name = data[i].name;
//data[i].dates = parseDate(data[i].dates);
if(!patientList[name]) {
var newPatient = {
dates: [data[i].dates],
alpha: data[i].alpha,
beta: data[i].beta
};
patientList[name] = newPatient;
} else {
patientList[name].dates.push(data[i].dates);
}
}
console.log(patientList);
console.log(Object.keys(patientList).length);
console.log(Object.keys(patientList));
});
}
function number_of_patients(callback) {
callback();
console.log(patientList);
console.log(Object.keys(patientList).length);
console.log(Object.keys(patientList));
}
number_of_patients(input_Data);
console.log inside the input_Data function displays correct results with length 4. And console.log in the number_of_patients displays correct patientList but 0 length and doesn't display name (keys) either. I have read similar posts but still can't fix the problem here.
Any help would be much appreciated.
In Javascript, generic objects do not have a length property.
Common facts about Javascript objects:
Objects contain key: value pairs where the keys are strings and values may be any type.
Objects do not have a .keys() method to get all of the keys, except...
Ecmascript 5 provides an Object.keys() which can be called explicitly as do some 3rd party libs like underscore.js
initialized using curly braces {} and key:value pairs
Before that, the usual way to count or access all of the keys unique to a specific instance of an object is with a loop like the following:
l=0;
for(var k in obj){
if (obj.hasOwnProperty(k)){
// hasOwnProperty ignores keys from the prototype chain
// do something with key k, value obj[k]
++l;
}
}
// the object has l keys specific to this instance
If you need to quickly get a length you should consider using an array object:
Array objects (x = [1,2,3,'sam',{'name':'fred', 'status': 'dead'}]) have numeric indices starting with 0 and can contain arbitrary type members.
have a length property (x.length is 5)
values are accessed by numeric indices with square brackets, i.e. x[2] is 3
initialized use square brackets [] containing a comma separated list of values
And as others said in comments, asynchronous calls generally return immediately -- and without the data or object you want in scope. To access the data you must execute code in the context where the data is defined, i.e. write code that accesses the asynchronous data/object in a callback function, not the main code.

Iterating over sparse arrays [duplicate]

This question already has answers here:
How should I iterate over a sparse array in index order?
(2 answers)
Closed 6 years ago.
This answer says that the best way to iterate over sparse arrays is to use for X in Array
However, when I tried this I tripped up because the type of X was a string, rather than the integer index I was expecting. (All fine until I added it to another integer...)
var arr = [];
arr[10000] = "Hello";
var shifted = []
for (var x in arr)
shifted[10+x] = arr[x];
"Expected":
shifted[10010] = "Hello
Actual
shifted["1010000"] = "Hello"
Is there a better way of iterating a sparse array using the index, or should I just use Number(X) where required?
This is how V8 (and others JavaScript engines) handles arrays:
V8 uses two different methods to handle arrays:
Fast elements:
Designed for arrays where set of keys are very compact. They have a linear storage buffer that can be accessed very efficiently.
Dictionary elements:
Designed for sparse arrays which don’t have every elements inside of them. It is actually a hash table, more expensive to access than “Fast Elements”
Source: http://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/
When you are using a sparse array, the key is converted to string and then hashed. If you want numeric keys: don't use a sparse array or manually convert the key to a number.

Categories