0

I have small issue, but can't solve it.As for me it should work, but i miss something: here is js code in one of angularJs controllers:

  function reorderItems(items, firstId) {
        var orderedItems = [];
        //I pass just 2 objects !!!
        console.log(items[0]);   // Object {children: Array[0], metadata: Array[6], state: Object, id: 226}
        console.log(items[1]); // Object {children: Array[0], metadata: Array[6], state: Object, id: 216}
        console.log(firstId);   // 216
        var firstItem ;
        for (var i = 0; i<items.length; i++) {
            if (items[i].id == firstId) {
                firstItem = items[i];
            }
        }
        orderedItems.push(firstItem);
        console.log(orderedItems);  // [Object] - length 1 !!!!

  }

to this part it work good. enter image description here BUT when I push again the same 'firstItem'.

        orderedItems.push(firstItem);
        console.log(orderedItems);

Why? I need to put in array first 216, and after it any other Item. enter image description here

2
  • Please create a minimal reproducible example demonstrating the problem here on-site with Stack Snippets (the <> toolbar button). You may just be running into this issue, but we can't tell from the above. Commented Aug 16, 2016 at 15:09
  • 1
    Side note about your loop: 1. You keep going even after you find the item, is that intentional? E.g., are these "IDs" not, in fact, unique, and you want the last one? 2. If it doesn't find anything, you're pushing undefined into your orderedItems array. Do you want to do that? Commented Aug 16, 2016 at 15:10

1 Answer 1

1

Try this function. It uses $filter to take out the first value and then add the rest.

  function reorderItems(items, firstId) {
        var orderedItems = [];

        var firstItem = $filter('filter')(items, {id: firstId})[0];
        orderedItems.push(firstItem);

        for (var i = 0; i<items.length; i++) {
            if (items[i].id != firstId) {
               orderedItems.push(items[i]);
            }
        }        
  }
Sign up to request clarification or add additional context in comments.

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.