0

Im trying to swap two array elements in an array that looks like this

[18785:Object, 22260:Object, 22261:Object, 22262:Object, 22263:Object]

I used the following code:

    that.moveMediumDown = function(mediumID){

        var arrKeys = new Array();

        for (key in that.data.medium) {
            arrKeys.push(parseInt(key));
        }

        for (var i = 0; i < arrKeys.length; i++){
            if (arrKeys[i] === parseInt(mediumID)) {

                //swap Medium
                var tmpMedium = that.data.medium[arrKeys[i]];
                that.data.medium[arrKeys[i]] = that.data.medium[arrKeys[i + 1]];
                that.data.medium[arrKeys[i + 1]] = tmpMedium;

                break;
            }
        }

        //build new array with correct ids

        var tmpMediumArray = new Array();

        for (var j = 0; j < arrKeys.length; j++){
            tmpMediumArray[arrKeys[j]] = that.data.medium[arrKeys[j]];
        }
    }

The problem is when I swap the content of the two array elements, the key stays the same. But I need also to swap the key.

So i tried to build a new array with the correct keys but then I get an Array with 22263 elements. Most of them are undefined and only the 5 are correct.

Is there any method to do this without getting such a big array?

Thanks in advance for your help.

0

1 Answer 1

1

Checkout the array_flip function.

It allows you to swap keys with the elements:

array_flip( {a: 1, b: 1, c: 2} );

becomes

{1: 'b', 2: 'c'}

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

8 Comments

Thanks for the answer. But I try to swap elements and not to flip keys and values. Or did I miss something?
Maybe I misunderstand what you mean by "swap elements"? You're trying to swap the keys as arrKeys with the array elements, so it's the same.
I try to swap the element at position 1 in the array with the element at position 3 for example. [18785:Object, 22260:Object, 22261:Object, 22262:Object, 22263:Object] -> [ 22261:Object, 22260:Object, 18785:Object, 22262:Object, 22263:Object]
Why? Are you sorting them? It'd be easier to change their sorting when this array is actually created, but it's possible you don't have access to that.
So is there no easy way to do this? The problem is more complex than I explained in my question. But I thought there should be an easy solution to swapping two elements.
|

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.