Move a particular value object in array to end

有些话、适合烂在心里 提交于 2019-12-25 18:16:52

问题


I'm trying to find a way to move an object to the end of the array

I have this array of objects:

[
  {"id":"4","name":"Boaz"},
  {"id":"2","name":"Shareen"},
  {"id":"3","name":"Simon"},
  {"id":"1","name":"Miriam"}
]

I want to move the whole set {"id":"3","name":"Simon"} to the end of it all. I have solution for this here. But my problem is every time that particular object is not coming in second position is there a way to check the object of id=3 and shift that to end using underscoreJS


回答1:


You can just sort array.

Explanation

Array.sort expects 3 possible values as return value.

  • 1: means a is greater than b and a will be move to a higher index than b
  • 0: means a is equal to b and no change will be made.
  • -1: means a is less than b and a will be move to a lower index than b.

For more information please refer: How does Javascript's sort() work?

var data = [
  {"id":"4","name":"Boaz"},
  {"id":"2","name":"Shareen"},
  {"id":"3","name":"Simon"},
  {"id":"1","name":"Miriam"}
]

data.sort(function(a,b){
  return a.id == 3 ? 1 : 0
})

console.log(data)

An alternate method could to filter out objects with necessary id, remove them from current position and the push them back, but this is too much work in my understanding. Sort is ideal way to move object up or down the order.




回答2:


Do some simple array manipulation

var obj = [{
    "id": "4",
    "name": "Boaz"
  },
  {
    "id": "2",
    "name": "Shareen"
  },
  {
    "id": "3",
    "name": "Simon"
  },
  {
    "id": "1",
    "name": "Miriam"
  }
];
obj.forEach(function(v, i) {
  if (v.id == 3) {//test to see if the id is 3
    obj.push(obj[i]);//push the object to the last position
    obj.splice(i, 1);//remove the object from the current position

  }

});
console.log(obj);



回答3:


function findIdIndex(id, array) {
  return array.findIndex(elem=>elem.id===id);
}

This will give you the position of the set with the given id, the answer to your previous question covers the rest of what you want to do.




回答4:


While there isnt an "out-of-the-box" underscore function, we can extend the base library with our own function using the _.mixin() function.

The extension works by using the underscore _.indexOf() function to return the index of an element that matches a predicate. We then use the native JS splice function, to remove 1 item at the returned index (Note that this will leave the array unaffected if _.indexOf returns -1). As per the docs, splice, returns an array of all elements that were removed. We, lastly use the native JS concat function, which merges two (or more) arrays together, to put the returned value from the concat on to the end of the supplied array (arr).

UnderscoreJS extending

(function(_) {
    "use strict";
    _.mixin({
        moveToEndWhere: moveToEndWhere
    });

    /**
     * @function moveToEndWhere
     * @desc Searches an array for the first item matching a predicate, and moves the matched element to the end of the array
     * @param {array} arr Array to be searched and altered
     * @param {function|object} predicate Function or object used to search for matching element
     * @returns {array} Updated array
     * @memberof _.mixin
     */
    function moveToEndWhere(arr, predicate){
        return arr.concat(
            arr.splice(
                _.indexOf(arr, predicate)
                , 1
            )
        );
    }
})(_);

Usage

var data = [
    {"id":"4","name":"Boaz"},
    {"id":"2","name":"Shareen"},
    {"id":"3","name":"Simon"},
    {"id":"1","name":"Miriam"}
];

data = _.moveToEndWhere(data, {"id":3});



回答5:


I suggest to use the delta of the comparison, not only if you have more than one true comparison, but you need a symetrically comparison, if b contains the item to sort at the end, then you get the order, you want.

var array = [{ id: "4", name: "Boaz" }, { id: "2", name: "Shareen" }, { id: "3", name: "Simon" }, { id: "1", name: "Miriam" }];

array.sort(function (a, b) {
    return (a.id === '3') - (b.id === '3');
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }



回答6:


first write a method like this,send the value as '3' and get the index and attr as id

function getElementIndex(array, attr, value) {
    for(var i = 0; i < array.length; i += 1) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}

By this method you can use any property to get the data with.

Then write

var index=getElementIndex(array,'id','3');//here array is your data array you have 
var itemToReplace = array.splice(index, 1); 

array = array.concat(itemToReplace);



回答7:


Can you try this with the getting index of the respective object and then check the position:

var array  = [{ "id": "4", "name": "Boaz" }, { "id": "2", "name": "Shareen" }, { "id": "3", "name": "Simon" }, { "id": "1", "name": "Miriam" }];

var index =  array.findIndex(x => x.id == 3);

if(index === 2) {
 var person =  array.splice(index, 1);
 array  = array.concat(person);
}

console.log(array)


来源:https://stackoverflow.com/questions/42479079/move-a-particular-value-object-in-array-to-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!