admin管理员组

文章数量:1415697

I have an array of objects that I get from an API and 1 of the objects has a "selected" property. I need to slice that array to only have 3 objects and 1 of the objects needs to be the "selected" object. I'm using lodash in an angular application but I'm not limited on how to achieve this, although I would prefer an answer that uses lodash. Thanks in advance... See example below:

//Sample array
var fruits = [{
  id: 1,
  fruit: "apple",
  selected: false
}, {
  id: 2,
  fruit: "pear",
  selected: false
}, {
  id: 3,
  fruit: "orange",
  selected: false
}, {
  id: 4,
  fruit: "pineaple",
  selected: false
}, {
  id: 5,
  fruit: "mango",
  selected: true
}, {
  id: 6,
  fruit: "peach",
  selected: false
}, {
  id: 7,
  fruit: "strawberry",
  selected: false
}];

I have an array of objects that I get from an API and 1 of the objects has a "selected" property. I need to slice that array to only have 3 objects and 1 of the objects needs to be the "selected" object. I'm using lodash in an angular application but I'm not limited on how to achieve this, although I would prefer an answer that uses lodash. Thanks in advance... See example below:

//Sample array
var fruits = [{
  id: 1,
  fruit: "apple",
  selected: false
}, {
  id: 2,
  fruit: "pear",
  selected: false
}, {
  id: 3,
  fruit: "orange",
  selected: false
}, {
  id: 4,
  fruit: "pineaple",
  selected: false
}, {
  id: 5,
  fruit: "mango",
  selected: true
}, {
  id: 6,
  fruit: "peach",
  selected: false
}, {
  id: 7,
  fruit: "strawberry",
  selected: false
}];

Expected result:

var fruits = [{
  id: 1,
  fruit: "apple",
  selected: false
}, {
  id: 2,
  fruit: "pear",
  selected: false
}, {
  id: 5,
  fruit: "mango",
  selected: true
}];

Share Improve this question edited May 27, 2016 at 15:57 Daniel Perez asked May 27, 2016 at 15:46 Daniel PerezDaniel Perez 231 gold badge1 silver badge6 bronze badges 2
  • it is unclear the criteria needed to select the other 2 items. Should it be random, start with the true one and get the rest. Is it always 3? – Rob Allen Commented May 27, 2016 at 15:50
  • Yes, the other ones can be picked at random, there is also an ID property that we can sort them by if we want to. I have updated the example. – Daniel Perez Commented May 27, 2016 at 15:55
Add a ment  | 

6 Answers 6

Reset to default 1

Making like 3 assumptions here, but:

var sliced = fruits.slice(0,3);

for (var i=3; i<fruits.length; i+=1)
    if (fruits[i].selected)
        sliced[0] = fruits[i];

Never understood the appeal of underscore or lodash post IE8. Tons of excellent convenience methods are available in modern JS. More on native JS array methods here: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

    //Sample array
    var fruits = [{
      fruit: "apple",
      selected: false
    }, {
      fruit: "pear",
      selected: false
    }, {
      fruit: "orange",
      selected: false
    }, {
      fruit: "pineaple",
      selected: false
    }, {
      fruit: "mango",
      selected: true
    }, {
      fruit: "peach",
      selected: false
    }, {
      fruit: "strawberry",
      selected: false
    }];

function fruitCheck(obj){
    var isDesiredFruit = (obj.fruit === 'mango') ||
        (obj.fruit === 'peach') ||
        (obj.fruit === 'strawberry');
    return isDesiredFruit;
}

var filteredFruits = fruits.filter(fruitCheck);

Give this a shot:

function getThreeFruits (fruits) {
  var split = _.partition(fruits, { selected: true })
  var selectedFruit = split[0]
  var twoOtherFruits = split[1].slice(0, 2)
  return selectedFruit.concat(twoOtherFruits)
}

Lots of ways to go about this! This is another Vanilla Javascript one, fill free to mix and match according to your actual specs.

var fruits = [{
  fruit: "apple",
  selected: false
}, {
  fruit: "pear",
  selected: false
}, {
  fruit: "orange",
  selected: false
}, {
  fruit: "pineaple",
  selected: false
}, {
  fruit: "mango",
  selected: true
}, {
  fruit: "peach",
  selected: false
}, {
  fruit: "strawberry",
  selected: false
}];

var selectedFruits = fruits.reduce((result, el) => {
  if(el.selected) {
    return Array(el).concat(result).slice(0, 3);
  }
  if (result.length > 2) return result;
  result.push(el);
  return result;
}, Array());

console.log(selectedFruits);
var z= _.sortBy(fruits,function(obj){return obj.selected})
var result.push(z.slice(0,2));
result.push(z[z.length-1]);

After Reviewing all the answers I decided to use something like this.

return user.userStoreAccesses
  .reduce(function(arr, el) {
    //check if current obj is the defaultStore
    if (el.defaultStore) {
      return [el].concat(arr).slice(0, 3);
    }
    //the moment the array is greater than 2 stop execution
    if (arr.length > 2) {
      return arr;
    }
    //keep pushing items to the array until...
    arr.push(el);
    return arr;
  }, []);

However I decided to go a little simpler than that by chaining a few lodash methods (which was my original intention). Here is the final result:

return _(user.userStoreAccesses)
  .chain()
  .sortBy("defaultStore")
  .reverse()
  .slice(0, 3)
  .value();

Thanks for the answers, they were very helpful!! I hope my method is also useful for somebody else :)

本文标签: javascriptLodash slice array and keep a specific itemStack Overflow