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

Serhiy
  • 1,893
  • 9
  • 30
  • 48
  • Please create a [mcve] demonstrating the problem here on-site with Stack Snippets (the `<>` toolbar button). You may just be running into [this issue](http://stackoverflow.com/questions/38660832/element-children-has-elements-but-returns-empty-htmlcollection), but we can't tell from the above. – T.J. Crowder Aug 16 '16 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? – T.J. Crowder Aug 16 '16 at 15:10

1 Answers1

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]);
            }
        }        
  }
cullimorer
  • 755
  • 1
  • 5
  • 23