如果值不满足给定条件,如何将其他数组元素包含到新数组中

时间:2017-10-25 00:15:59

标签: javascript angular ecmascript-6

我这里有1个数组。如何在JavaScript中执行此逻辑

费率列表示例:

  var rates : [ 
   {id:1,value:7},  
   {id:2,value:7},
   {id:3,value:7},
   {id:4,value:6},
   {id:5,value:6},
   {id:6,value:5},
   {id:7,value:4},
  ]

条件是获得前5名的比率。最高为7 ..如果7比5少,则包括6。如果所有费率都小于5.包括费率5.

注意:如果费率7小于5。所有费率都可以超过5.见另一种情况

预期产出

{id:1,value:7},  
  {id:2,value:7},
  {id:3,value:7},
  {id:4,value:6},
  {id:5,value:6},

其他方案

 var rates : [ 
       {id:1,value:7},  
       {id:2,value:7},
       {id:3,value:7},
       {id:4,value:7},
       {id:5,value:5},
       {id:5,value:5},
       {id:5,value:5},
       {id:6,value:4},
       {id:7,value:4},
      ]

输出

{id:1,value:7},  
{id:2,value:7},
{id:3,value:7},
{id:4,value:7},
{id:5,value:5},
{id:5,value:5},
{id:5,value:5},

非常感谢你的帮助

2 个答案:

答案 0 :(得分:1)

以下是您的问题的psudo代码答案:

/*Sort the rates highest to lowest by value*/

/*Create a new array to store your top rates*/

/*iterate over your rates */

    /* If there are less than 5 topRates go ahead and add the rate
       to top rates. 
       Remember rates is now sorted highest to lowest value
    */

    /* else if we have the top 5 already, check to see if
       the current rate is equal to the last top rate
    */

    /* otherwise our topRates has more than 5 and the next rate is 
       not the same value of our last top rate break out of the loop
    */

答案 1 :(得分:1)



@Override
public void onRequestPermissionResult(/*params*/){
    PermissionsService.onRequestPermissionResult(/*params*/);
}

function orderAscendingById(a, b) {
  return (((a.id < b.id) && -1) || ((a.id > b.id) && 1) || 0);
}

function orderDescendingByValue(a, b) {
  return (((a.value > b.value) && -1) || ((a.value < b.value) && 1) || 0);
}


function getTopMostRated(ratingList) {
  ratingList = Array.from(ratingList);  // - do not mutate the original reference.
  ratingList.sort(orderAscendingById).sort(orderDescendingByValue); // - sanitize.
  var
    ratedList = ratingList.slice(0, 5), // - less items 1st.
    lastItem  = ratedList[4];           // - pick last item.

  if (lastItem && (lastItem.value <= 5)) {  // - check condition for item count.
    ratedList = ratingList.slice(0, 7);     // - allow more items.
  }
  return ratedList;   // return ordered and trimmed rating result.
}


var rates = [
  { id: 7, value: 4 },
  { id: 6, value: 4 },
  { id: 5, value: 5 },
  { id: 5, value: 5 },
  { id: 5, value: 5 },
  { id: 4, value: 7 },
  { id: 3, value: 7 },
  { id: 2, value: 7 },
  { id: 1, value: 7 }
];
var result = getTopMostRated(rates);

console.log('rates : ', rates);
console.log('result : ', result);


rates = [ 
  { id: 7, value: 4 },
  { id: 6, value: 5 },
  { id: 5, value: 6 },
  { id: 4, value: 6 },
  { id: 3, value: 7 },
  { id: 2, value: 7 },
  { id: 1, value: 7 }
];
result = getTopMostRated(rates);

console.log('rates : ', rates);
console.log('result : ', result);
&#13;
&#13;
&#13;