javascript-根据属性重新排列对象的数组

时间:2018-08-23 11:35:14

标签: javascript arrays sorting

我正在为网页构建选择下拉输入。我想创建一个“热门”选项组,该选项组显示在下拉菜单的顶部。

我正在使用以下结构的数据。 我需要找到一种方法,可以根据人员名称对人员数组中的项目进行重新排序。

例如移动:
玩具高跷[2]->玩具[0]
从玩具[3]到玩具[2]的卡片

我将拥有一系列受欢迎的玩具,例如:

popularToys: [
    "cards", "pogo-stick"
]

如何遍历对象数组并将它们移至新顺序?

数据:

{
  "toys": [
    {
      "name": "car",
      "price": "10"
    },
    {
      "name": "duck",
      "price": "25"
    },
    {
      "name": "pogo-stick",
      "price": "60"
    },
    {
      "name": "cards",
      "price": "5"
    }
  ]
}

4 个答案:

答案 0 :(得分:1)

使用current_plus_2_hours = time.time() + 2 * 60 * 60 循环,您可以在其中找到玩具对象的forEach()并交换:

index

答案 1 :(得分:1)

使用mapfilter的组合,我们可以将所需的逻辑拆分为方法(也许更具可读性)

Popular()返回具有name属性的任何玩具项的过滤数组,该属性与popular迭代中的当前名称相对应

Rest()返回过滤后的toys数组,其中玩具中name的迭代属性在popular的字符串数组中不存在

const toys = [
  {
    name: 'car',
    price: '10'
  },
  {
    name: 'exception',
    price: '999999'
  },
  {
    name: 'duck',
    price: '25'
  },
  {
    name: 'pogo-stick',
    price: '60'
  },
  {
    name: 'cards',
    price: '5'
  },
  {
    name: 'another !exception',
    price: '100000'
  },
  {
    name: 'pogo-stick',
    price: 'A MILLION POUNDS'
  },
  {
    name: 'duck',
    price: '100'
  }
]

const popular = [
  'cards', 
  'pogo-stick', 
  'car', 
  'duck'
]

const Popular = () => {
  return [].concat(...popular.map(n => toys.filter(({name}) => name === n)))
}
const Rest = () => toys.filter(({name}) => popular.indexOf(name) === -1)

let ordered = [].concat(...Popular(), ...Rest())

console.log(ordered)

答案 2 :(得分:1)

您可以使用自定义排序功能

var popularToys = [
    "cards", "pogo-stick"
]

var data = {
  "toys": [
    {
      "name": "car",
      "price": "10"
    },
    {
      "name": "duck",
      "price": "25"
    },
    {
      "name": "pogo-stick",
      "price": "60"
    },
    {
      "name": "cards",
      "price": "5"
    }
  ]
};

function popularFirst(a, b) {
  var aIsPopular = popularToys.indexOf(a.name) > -1;
  var bIsPopular = popularToys.indexOf(b.name) > -1;
 
  if (aIsPopular) {
    // b could be popular or not popular, a still comes first
    return -1;
  } else if (bIsPopular) {
    // a isnt popular but b is, change the order
    return 1;
  } else {
    // no change
    return 0;
  }
}

console.log(data.toys.sort(popularFirst));

答案 3 :(得分:-2)

    function compare(a,b) {
      if (a.name < b.name)
         return -1;
      if (a.name > b.name)
         return 1;
    return 0;
    }

toys.sort(compare);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort