Javascript 在数组中排序CSV字符串,不包括零索引

Javascript 在数组中排序CSV字符串,不包括零索引,javascript,reactjs,sorting,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,Ha

我在一个数组中有逗号分隔的值,我从一个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>
          )
        }
      }

此外,我还想按列排序,就像我单击年份首席执行官它应该按年份或首席执行官排序一样。每一列都一样。

下面是如何做到这一点的

  • 首先将字符串数组转换为数组数组
  • 然后使用
    slice(1)
    获取除标题之外的所有行
  • 对切片(1)
  • 函数show take a parameter
    colno
  • sort()
    中,您应该比较
    colno
  • 返回之前,在排序数组之前添加标题
    arr[0]
  • 让arr=[
    “公司、行业、年份、首席执行官”,
    “特斯拉,汽车,15,埃隆”,
    “SpaceX,航空航天,17,埃隆”,
    “亚马逊,软件,24岁,杰夫”,
    “谷歌,软件,20,圣达”,
    “微软,软件,30,Satya”,
    “宝马,汽车,103,哈拉尔德”,
    “蓝源航空,19岁,杰夫”,
    “美国宇航局,太空,61,政府”,
    “超环线,运输,5号,埃隆”
    ]
    函数排序(arr、colno){
    设x=arr.map(x=>x.split(',').map(a=>Number(a)| | a));
    返回[x[0].concat(x.slice(1).sort((a,b)=>{
    if(a[colno]='number'的类型){
    返回a[colno]-b[colno];
    }
    否则返回a[colno].localeCompare(b[colno]);
    })).map(x=>x.join(','))
    }
    
    log(sort(arr,1))
    我建议在
    render()函数中构建html元素。这样做将使您能够访问React的数据绑定和事件侦听语法,使其更易于维护,并提高大型表的性能

    这可以通过将CSV数据解析为对象并将其存储到
    This.state.data
    中来实现。键是标题,值是数据点

    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;
        };
      }
    
    
    
    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'}
    ];
    //单击表格标题并传递键以根据(例如公司)进行排序
    索特比(钥匙){
    让arrayCopy=[…this.state.data];
    arrayCopy.sort(this.compareBy(key));
    this.setState({data:arrayCopy});
    }
    比较(键){
    返回函数(a,b){
    如果(a[key]b[key])返回1;
    返回0;
    };
    }
    
    以下是我的解决方案:

    我希望这有帮助

    // 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'));
    
    //babel.js
    /*
    *行组件
    */
    常量行=(行)=>(
    {
    //将对象的值映射到HTML
    //**注意:假设键/值将以相同的顺序保留
    Object.values(rows.map((r)=>{r})
    }  
    );
    /*
    表组件
    */
    类表扩展了React.Component{
    建造师(道具){
    超级(道具);
    此.state={
    数据:[
    //输入示例:
    //{'Company':'Tesla','Industry':'Automobile','Years':'15','CEO':'Elon'},
    //{'Company':'SpaceX','Industry':'AeroSpace','Years':'17','CEO':'Elon'},
    //{'Company':'NASA','Industry':'Space','Years':'61','CEO':'Gov'}
    ],
    //向http GET请求添加服务/ajax调用,以从服务器/后端获取csv
    文件:[
    “公司、行业、年份、首席执行官”,
    “特斯拉,汽车,15,埃隆”,
    “SpaceX,航空航天,17,埃隆”,
    “亚马逊,软件,24岁,杰夫”,
    “谷歌,软件,20,圣达”,
    “微软,软件,30,Satya”,
    “宝马,汽车,103,哈拉尔德”,
    “蓝源航空,19岁,杰夫”,
    “美国宇航局,太空,61,政府”,
    “超环线,运输,5号,埃隆”
    ]
    };
    this.parseCsv();
    this.compareBy.bind(this);
    这个。肮脏。捆绑(这个);
    }
    parseCsv(){
    const{file}=this.state;
    如果(文件!==“”){
    //从索引0设置标题
    让headers=文件[0]。拆分(',).map(值=>value);
    //临时从For循环中删除索引0
    file.slice(1).forEach((行)=>{
    让items=row.split(',');
    设d={};
    items.forEach((项目,索引)=>{
    //分析数字以进行适当排序,例如“3”->3
    如果(/^[0-9]+$/.test(item))item=parseInt(item)
    //关键词:公司,价值:特斯拉
    d[标题[索引]]=项目;
    //完成解析后,添加到state.data
    如果(索引+1==items.length){
    这个.state.data.push(d);
    log(JSON.stringify(d));
    }
    })
    })
    }
    }
    比较(键){
    返回函数(a,b){
    如果(a[key]b[key])返回1;
    返回0;
    };
    }
    索特比(钥匙){
    让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)=>);
    返回(
    {
    headers.map((h)=>this.sortBy(h)}>{h})
    }
    {rows}
    );
    }
    }
    /*
    *渲染组件
    */
    ReactDOM.render(,document.getElementById('app'));
    
    
    
    请输入预期输出?当我单击标题(其列为公司、行业、年份和首席执行官)时,它应该对数组的其余部分进行排序,不包括
    0th index
    ,该标题根据单击的列处于状态。如果我单击“公司”,则根据公司对数组进行排序,如果我单击“年份”,则根据年份对数组进行排序。我已经回答了这个问题,并给出了使用字符串数组和要排序的列编号的通用函数。如果有问题,请告诉我这也是一个很好的解决方案,但是年份列的排序不正确。捕捉得好!它是按字符编码排序的,而不是数年的值。我会编辑这篇文章来修复这个错误。嗨,你能帮我修改一下吗
    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;
        };
      }
    
    
    
    // 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'));