Answer the question
In order to leave comments, you need to log in
How to sort objects?
There is an "array" of objects.
var a = {
q_1: {
_next: "w_2",
_prev: "u_7"
},
w_2: {
_next: "e_3",
_prev: "q_1"
},
e_3: {
_next: "r_4",
_prev: "w_2"
},
r_4: {
_next: "t_5",
_prev: "e_3"
},
t_5: {
_next: "y_6",
_prev: "r_4"
},
y_6: {
_next: "u_7",
_prev: "t_5"
},
u_7: {
_next: "q_1",
_prev: "y_6"
}
}
I don't want to keep 1 more array in memory with active element index. Plus, I have more properties in this object that are not related to the elements that need to be sorted. I believe that you need to change the values of the properties "_next" and "_prev" in the elements themselves. The question is how best to do it?
Answer the question
In order to leave comments, you need to log in
And how are you going to restore the previous sorting by these keys? You then have to create directly in the elements properties like "array_of_previous_next", etc., you still have to store information about sorting somewhere. Therefore, it is more logical to separate sorting from the logic of the object, the maximum is to give the objects either a unique name or an ID, something like this:
var array_of_orders = [],
current_order = 0,
objects = [
{ name: 'q_1' },
{ name: 'w_2' },
{ name: 'e_3' },
{ name: 'r_4' },
{ name: 't_5' },
{ name: 'y_6' },
{ name: 'u_7' }
];
array_of_orders.push( objects.map(function(object) { return object.name; }) );
function sort(sort_function) {
objects.sort(sort_function || function() { return Math.random() - 0.5; });
array_of_orders.push( objects.map(function(object) { return object.name; }) );
current_order = array_of_orders.length - 1;
}
function applyOrder(index) {
var order = array_of_orders[index],
result, name_to_find, i, k, l;
if ( order ) {
l = order.length;
result = Array( l );
for (i = 0; i < l; i++) {
name_to_find = order[i];
for (k = 0; k < l; k++) {
if (objects[k].name === name_to_find) {
result[i] = objects[k];
}
}
}
objects = result;
current_order = index;
}
};
You do not have an array, but an object, and objects have random access to elements by their key.
Keys as such can be obtained in the form of an array or by the Object.keys function, which receives all enumerable keys of an object, including keys from the prototype chain (non-enumerable properties include those declared through Object.defineProperty, except for explicitly specifying enumerable: true, as well as symbols (Symbol) and methods ( { method() { ... } } ) from ES2015), or by the Object.getOwnPropertyNames function, which gets all the object's own keys, except for symbols (prototype is excluded, enumerable is not taken into account)
Random array shuffling is done elementarily: arr.sort(() => Math.random() - 0.5);
As a result, you can get an array of your object's keys in random order:
var keys = Object.keys(a).sort(() => Math.random() - 0.5);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question