javascript - 对不包括零索引的数组中的 CSV 字符串进行排序

标签 javascript reactjs sorting

我从 CSV 文件获取的数组中有逗号分隔值,并使用它在 React 中显示表格。

[
"Company,Industry,Years,CEO", 
"Tesla,Automobile,15,Elon", 
"SpaceX,AeroSpace,17,Elon", 
"Amazon,Software,24,Jeff", 
"Google,Software,20,Sundar", 
"Microsoft,Software,30,Satya", 
"BMW,Automobile,103,Harald", 
"BlueOrigin,AeroSpace,19,Jeff", 
"NASA,Space,61,Gov", 
"Hyperloop,Transportation,5,Elon"
]

JSX

  renderCsvTable() {
        const { file } = this.state;
        if(file !== "") {
          let data = `<table className="csv-table">`;
          file.forEach((cells, i) => {
            let cell_data = cells.split(',');
            data+= `<tr>`;
            cell_data.forEach((column) => {
              if (i === 0) {
                data+= `<th>${column}</th>`;
              } else {
                data+= `<td>${column}</td>`;
              }
            });
            data+= `</tr>`;
          });
          data+= `</table>`;

          return (
            <div>{ parse(data) }</div>
          )
        }
      }

我想根据单独的列对我的数组进行排序。

目前我可以使用排序方法按第一列排序

this.state.file.sort((a, b) => (a > b) - (a < b));

但它也在对数组的 [0] 索引 进行排序,我不想这样做,因为它是表的标题。

排序后

[
"Amazon,Software,20,Jeff", 
"BMW,Automobile,33,Harald", 
"BlueOrigin,Space,4,Jeff", 
"Company,Industry,Years,CEO", 
"Google,Software,30,Sundar", 
"Hyperloop,Transportation,5,Elon", 
"Microsoft,Software,30,Satya", 
"NASA,Space,60,Gov", 
"SpaceX,Space,5,Elon", 
"Tesla,Automobile,10,Elon"
]

我还想按列排序,如果我点击 YearsCEO 它应该按年或 CEO 排序。每一列都一样。

最佳答案

我建议在 render() 函数中构建 html 元素。这样做将使您能够访问 React 的数据绑定(bind)和事件监听语法,使其更易于维护,并提高大型表的性能。

这可以通过将 CSV 数据解析为对象并将其存储到 this.state.data 中来完成。键是 header ,值是数据点。

this.state.data =[
  {'Company':'Tesla','Industry':'Automobile','Years':'15','CEO':'Elon'},
  {'Company':'SpaceX','Industry':'AeroSpace','Years':'17','CEO':'Elon'},
  {'Company':'NASA','Industry':'Space','Years':'61','CEO':'Gov'}
];

  // on click of table heading and pass the key to sort based on (ex. company)
  sortBy(key) {
    let arrayCopy = [...this.state.data];
    arrayCopy.sort(this.compareBy(key));
    this.setState({data: arrayCopy});
  }


  compareBy(key) {
    return function (a, b) {
      if (a[key] < b[key]) return -1;
      if (a[key] > b[key]) return 1;
      return 0;
    };
  }


这是我的解决方案:https://codepen.io/brettdawidowski/pen/drJEjb

希望对您有所帮助!

// babel.js

/*
 * Row Component
*/

const Row = (rows) => (
  <tr>
    {
      // Maping the values of Object to HTML <td>
      // **Note: Assuming the Keys/Values will persist in the same order
      Object.values(rows).map((r) => <td>{r}</td>)
    }  
  </tr>
);

/*
  Table Component
*/
class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [
        // Example Input: 
       // {'Company':'Tesla','Industry':'Automobile','Years':'15','CEO':'Elon'},
       // {'Company':'SpaceX','Industry':'AeroSpace','Years':'17','CEO':'Elon'},
      // {'Company':'NASA','Industry':'Space','Years':'61','CEO':'Gov'}

      ],
      // Add service/ajax call to http GET request to fetch csv from server/back-end
      file: [
      "Company,Industry,Years,CEO", 
      "Tesla,Automobile,15,Elon", 
      "SpaceX,AeroSpace,17,Elon", 
      "Amazon,Software,24,Jeff", 
      "Google,Software,20,Sundar", 
      "Microsoft,Software,30,Satya", 
      "BMW,Automobile,103,Harald", 
      "BlueOrigin,AeroSpace,19,Jeff", 
      "NASA,Space,61,Gov", 
      "Hyperloop,Transportation,5,Elon"
      ]
    };

    this.parseCsv();

    this.compareBy.bind(this);
    this.sortBy.bind(this);
  }

  parseCsv() {
    const { file } = this.state;
    if(file !== "") {

      // set headers from index 0
      let headers = file[0].split(',').map(value => value);

      // temp remove index 0 from For loop
      file.slice(1).forEach((row) => {
        let items = row.split(',');
        let d = {};
        items.forEach((item, index) => {
          // parse Numbers for proper sorting ex. “3” -> 3
          if(/^[0-9]+$/.test(item)) item = parseInt(item)
          // key: Company, value: Tesla
          d[headers[index]] = item;

          // When complete parsing add to state.data
          if(index + 1 === items.length) {
            this.state.data.push(d);
            console.log(JSON.stringify(d));
          }
        })
      })

    }
  }


  compareBy(key) {
    return function (a, b) {
      if (a[key] < b[key]) return -1;
      if (a[key] > b[key]) return 1;
      return 0;
    };
  }

  sortBy(key) {
    let arrayCopy = [...this.state.data];
    arrayCopy.sort(this.compareBy(key));
    this.setState({data: arrayCopy});
  }

  render() {
    const headers = Object.keys(this.state.data[0])
    const rows = this.state.data.map( (rowData) => <Row {...rowData} />);

    return (
      <table>
        <thead>
        <tr>
          {
            headers.map((h) => <th onClick={() => this.sortBy(h)}>{h}</th> )
          }
        </tr>
          </thead>
        <tbody>
          { rows }
        </tbody>
      </table>
    );

  }
}

/*
 * Render Component
 */
ReactDOM.render(<Table />, document.getElementById('app'));
<!-- index.html -->
<div id="app"></div>

关于javascript - 对不包括零索引的数组中的 CSV 字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55154710/

相关文章:

javascript - 取消突出显示菜单项

javascript - 在 if 语句中检查元素是否具有动态添加的类

javascript - 纯粹遵循 Redux 方式并进行 Dump |展示组件

javascript - 当它返回到第一次出现时发出警报

javascript - 我在 WebStorm 中找不到“在浏览器中打开”选项

javascript - 如何解决问题 目前未启用对实验性语法 'classProperties' 的支持

javascript - 将绑定(bind)函数 react 到数组中的每个项目

arrays - 保留每列的 n 个最大值,并在 MATLAB 中将其余值设置为零,无需循环

javascript - 按数字顺序对具有逗号分隔价格字符串的对象数组进行排序

python - 从按字母顺序排列的列表的索引为 0 的列表字典中对打印输出进行排序