Skip to content

Instantly share code, notes, and snippets.

@shadeglare
Last active December 27, 2015 01:29
Show Gist options
  • Save shadeglare/7245720 to your computer and use it in GitHub Desktop.
Save shadeglare/7245720 to your computer and use it in GitHub Desktop.
How to mimicry an Object ({ }) to an Array ([]) with index rearranging
var object = {
1: "lorem",
2: "ipsum",
3: "dolor",
4: "sit",
5: "amet"
};
var calculateKeyPosition = function(object, key) {
var props = Object.getOwnPropertyNames(object);
// indexOf uses strong comparing (===) and props are always string values
key = typeof(key) === typeof("") ? key : key.toString();
return props.indexOf(key);
};
var rearrangeKeys = function(object, startIndexPosition) {
var props = Object.getOwnPropertyNames(object);
for (var i = startIndexPosition; i < props.length; i++) {
var currentKey = parseInt(props[i]);
var nextKey = currentKey - 1;
var value = object[currentKey];
delete object[currentKey];
object[nextKey] = value;
}
};
var key = 1;
var position = calculateKeyPosition(object, key);
if (position !== -1) {
delete object[key];
rearrangeKeys(object, position);
}
console.log(object);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment