Reputation: 6276
If I have a javascript object that looks like the following:
{
0: [0,50],
1: [25,50],
2: [148,60]
}
How can I insert a new row at an index dependant on the value?
E.g. if the row I wish to insert contains the data [122,65] I need to test the value '122' versus the first value of all the the rows and then 'splice' the row in at the returned index. The second of each row value (50,50,50 in the example above) should not be taken into consideration. In this case the newd data should be inserted as row 2 since it is less than 148 and higher than 25... With the previous row 2 now becoming row 3.
I have been hunting high and low for an answer to this today and have stumbled across the following code which hints at the kind of functionality I am after, but does not quite work in this instance since if my understaning is correct, it only compares single numbers.
function findInsertionPoint(sortedArr, val, comparator) {
var low = 0, high = sortedArr.length;
var mid = -1, c = 0;
while(low < high) {
mid = parseInt((low + high)/2);
c = comparator(sortedArr[mid], val);
if(c < 0) {
low = mid + 1;
}else if(c > 0) {
high = mid;
}else {
return mid;
}
//alert("mid=" + mid + ", c=" + c + ", low=" + low + ", high=" + high);
}
return low;
}
/**
* A simple number comparator
*/
function numComparator(val1, val2) {
if(val1 > val2) {
return 1;
}else if(val1 < val2) {
return -1;
}
return 0;
}
I don't know if the above code will help anyone come up with a solution but I thought I would share it anyway. I am of course open to any javascript/jQuery method of achieving this.
Thank you.
Upvotes: 0
Views: 163
Reputation: 207521
This code could be improved greatly, but this really is a bandaid for a bad design.
var myObj = {
0: [0,50],
1: [25,50],
2: [148,60]
}
function makeArray( obj ) {
var newArray = [];
for( var x in obj ) {
newArray.push(obj[x]);
}
return newArray;
}
function makeObject( newArray ) {
var newObj = {};
for(var i=0, n=newArray.length; i<n; i++) {
newObj[i] = newArray[i];
}
return newObj;
}
function custSortFnc(a,b) {
return (a[0]==b[0]) ? a[1]>b[1] : (a[0] > b[0]) ? 1 : -1;
}
function addValue(val) {
var newArray = makeArray( myObj );
newArray.push( val );
newArray.sort( custSortFnc );
myObj = makeObject( newArray );
}
console.log(myObj);
addValue([122,65]);
for(var xx in myObj){
console.log(xx + ":" + myObj[xx]);
}
The looping will be bad if you add tons of elements to this thing. I also did not really check the sort function, it could be wrong.
Upvotes: 1
Reputation: 490283
This is never going to work properly as objects do not have a defined order for their properties.
Therefore, inserting a property in an order is not going to always work. Use an array if the order matters.
Upvotes: 1