Skip to content

Instantly share code, notes, and snippets.

@nikolas
Forked from mir4ef/insert-into-sorted-array.js
Last active January 15, 2020 20:12
Show Gist options
  • Save nikolas/d53a54ec2d32258844225b52e5c2d691 to your computer and use it in GitHub Desktop.
Save nikolas/d53a54ec2d32258844225b52e5c2d691 to your computer and use it in GitHub Desktop.
insert an element into a sorted array of objects
// 1d array
for (var i = 0, len = arr.length; i < len; i++) {
if (somevalue < arr[i]) {
arr.splice(i, 0, somevalue);
break;
}
}
return arr;
// an array of objects
var newObj = {
key: value
};
for (var i = 0, len = arr.length; i < len; i++) {
if (somevalue < arr[i].key) {
arr.splice(i, 0, newObj);
break;
} else if (i === arr.length - 1) {
// If this is reached, newObj belongs at the end
// of the array.
arr.push(newObj);
break;
}
}
return arr;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment