Skip to content

Instantly share code, notes, and snippets.

@mir4ef
Last active November 10, 2023 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mir4ef/2c41692c6112495e9caceaff70a5a54c to your computer and use it in GitHub Desktop.
Save mir4ef/2c41692c6112495e9caceaff70a5a54c 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;
}
}
return arr;
@AMR-aa1405465
Copy link

AMR-aa1405465 commented Feb 14, 2020

`

// an array of objects
function insertSorted(insertedObject,arr) {
let isLast=true;
if(arr.length===0)
arr.push(insertedObject)
else {
for (let i = 0, len = arr.length; i < len; i++) {
if (insertedObject.key < arr[i].key) {
isLast = false;
arr.splice(i, 0, insertedObject);
break;
}
}
if(isLast){
arr.push(insertedObject);//add to the end
}
}
return arr;
}
`
The above code doesnt handle adding to last or adding to front

@mungruez
Copy link

mungruez commented Mar 3, 2022

both solutions are bad ! Very Inefficient ! The array is sorted so why not use binary search to find the location where the new object must be placed.

@VincenLiu4587
Copy link

should consider to add the new one to last
let idx = pEligibleUsers.findIndex(obj => obj.DisplayName > pSelectedUserArray[myIndex].DisplayName);
if (idx == -1) {
//if the one should be the last item
pEligibleUsers.push(pSelectedUserArray[myIndex]);
} else {
pEligibleUsers.splice(idx, 0, pSelectedUserArray[myIndex]);
}

@mungruez
Copy link

should consider to add the new one to last let idx = pEligibleUsers.findIndex(obj => obj.DisplayName > pSelectedUserArray[myIndex].DisplayName); if (idx == -1) { //if the one should be the last item pEligibleUsers.push(pSelectedUserArray[myIndex]); } else { pEligibleUsers.splice(idx, 0, pSelectedUserArray[myIndex]); }

Errors in the splice statement in this code also I will have post my code when I repair my laptop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment