如何排序按字母顺序排列的属性值返回的蓄电池? - 使用Javascript [复制]

问题描述 投票:1回答:1

这个问题已经在这里有一个答案:

我想写一个JavaScript函数来显示多个下拉。正如你可以看到这一点。 State.data包含了整个API数据。这里this.state.data是对象的阵列。

我想作为排序依据的属性值返回累加器。值和标签是基本相同

  getOptions(propertyName) {
return this.state.data.reduce((accum, elem, i) => {
  const accumulator = [...accum];
  if(!accumulator.some((e) => { return e.value === elem[propertyName]; })) {
    if(elem[propertyName] !== '' && elem[propertyName] !== '-') {
      accumulator.push({
        id: i,
        value: elem[propertyName],
        label: elem[propertyName]
      });
    }
  }
  return accumulator;
}, []);
 }

我只想使用纯JS来做。我可以使用lodash但我不能使用jQuery。我更感兴趣的是使用纯香草JS

javascript
1个回答
0
投票

如果你想用一个比较函数使用一个特定的属性进行比较:

data.sort(function (a,b) {
    return a.propertyName > b.propertyName ? 1 : b.propertyName > a.propertyName ? -1 : 0;
})

而在一般情况如果要排序的字符串(不是对象)的按字母顺序排列只需拨打sort()上的数据。呼叫reverse(),如果你想在降序排列。

© www.soinside.com 2019 - 2024. All rights reserved.