如何消除 React Table - ReactJS/JavaScript 下拉列表中的重复值

How to eliminate duplicate values in dropdown of a React Table - ReactJS/JavaScript

我正在尝试使用 React Table 学习多过滤器。这是我的 Demo/Fiddle

我正在尝试消除 React 下拉列表中的重复值 Table

        <Select
          style={{ width: "50%", marginBottom: "20px" }}
          onChange={entry => {
            this.setState({ select2: entry });
            this.onFilteredChangeCustom(
              entry.map(o => {
                return o.value;
              }),
              "firstName"
            );
          }}
          value={this.state.select2}
          multi={true}
          options={this.state.data.map((o, i) => {
            return { id: i, value: o.firstName, label: o.firstName };
          })}
        />

我在下拉列表中得到了重复的值。请帮助我如何消除下拉列表中的重复值。

。如您所见,Sam 来了两次。

。 Jones1也来了两次

基本上我过滤每一列,上面的函数基本上处理过滤功能。请看截图。有一个问题 - 在我的 Json 数组中有一些值多次出现。但在下拉列表中,它们应该只出现一次。

编辑 1 - 我想要一个可以应用于任意数量下拉列表的通用解决方案。到目前为止,我已经得到了两个很好的答案。但这两个答案都不是一概而论的。我想将此独特功能扩展到所有列。我将有 15 到 20 列。这就是为什么我需要一个通用的解决方案。

var names = this.state.data.map((o, i) => {
  return o.firstName
})

var uniqueNames = names.filter(function(i, index){
    return names.indexOf(i) >= index
});

https://codesandbox.io/s/40n0jnzk5x 查看 firstdropdown

的修复

辅助函数

var uniqueOptions = (objectsArray, objectKey) => {

   var a = objectsArray.map((o, i) => {
     return o[objectKey]
   })

   return a.filter(function(i, index){
      return a.indexOf(i) >= index
   })
}

名字下拉菜单的用法(与任何其他下拉菜单相同)

      ....
      multi={true}
      options={this.uniqueOptions(this.state.data, 'firstName').map((name, i) => {
        return { id: i, value: name, label: name };
      })}
      ...

理想情况下,您会计算此外部渲染以防止在每次渲染时重新计算,但您明白了

试试这个

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

getOptions("FirstName")