0

I have an indexed of of objects:

indexArray = [
    {obj 1},
    {obj 2},
    ...
    {obj n}
];

I apply a sorting algorithm to it and the indexArray ends up being mixed up:

indexArray = [
    {obj 77},
    {obj 36},
    ...
    {obj 8}
];

If there was one element in the original array whose before and after Index I want to keep track of. For example, obj 36 was at index[35] before sorting, and the new index is index[1]. How would I determine the new index.

Could I hold on to the element/obj36 in a temp variable before the sort, and then after the sort, ask indexArray the current index of obj36? And if so, how?

2
  • Depends on your sorting algorithm. Are you using the javascript default sort? Commented Jul 16, 2012 at 5:22
  • Yes. I was just wondering there was more efficient way then temp variable and loop to find it. But I realize keeping a +- counter as the object moves position through array is worse. Commented Jul 16, 2012 at 5:30

2 Answers 2

1

Yes, using a temp variable to refer to it and then look for it in the sorted array can make the trick. You can use the Array.prototype.indexOf method if it's available or just loop to find it.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do this:

  • Create the array.
  • Copy it to another array.
  • Sort the original one.
  • Search for ocurrences of the itens of the sorted in the unsorted.

Take a look:

// original array of objects
var a = [{
    n: 5
}, {
    n: 3
}, {
    n: 7
}, {
    n: 1
}];

// create a copy of the original (concats the original with a empty one)
var b = a.concat([]);

// sorting
a.sort( function( left, right ) {
    return left.n - right.n;
});

// print a values
for ( var i in a ) {
    console.log( a[i].n );
}

// print b values
for ( var i in b ) {
    console.log( b[i].n );
}

// searching...
for ( var i in a ) {
    console.log( "value: " + a[i].n +
                 " original index: " + b.indexOf(a[i]) +
                 " current index: " + i );
}

Take a look here for some info about Array functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.