Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2014年12月24日 D5 #32

Open
nunnly opened this issue Dec 24, 2014 · 2 comments
Open

2014年12月24日 D5 #32

nunnly opened this issue Dec 24, 2014 · 2 comments
Labels

Comments

@nunnly
Copy link
Owner

nunnly commented Dec 24, 2014

写一个csvColumns函数,传入一个类似CSV(如下所示格式)的数组,和索引,数组代表该CSV的列和行,并返回该索引所对应数组中指定的列。

//在CSV格式示例如下:“1,2,3\ n4,5,6\ n7,8,9\ n10,11,12”
//应该被被转换成:
[1,2,3]
[4,5,6]
[7,8,9]
[10,11,12]
//返回对应下标的所有数字
csvColumns( "1,2,3\n4,5,6" , [0, 1] ) => returns "1,2\n4,5" 
csvColumns( "1,2\n3,4\n5,6" , [5, 6, 7] ) => returns "" 
csvColumns( "a,b,c,d,e\n1,2,3,4,5\nf,g,h,i,j" , [1, 3, 5, 7] ) => returns "b,d\n2,4\ng,i"

// param1 String
// param2 Array
// return String
function csvColumns(csv, indices){
  //TODO 
}
@think2011
Copy link
Collaborator

function csvColumns(csv, indices){
    var results = [];

    // 得到csv转换的数组
    var csvArr = csv.split('\n').map(function (v,k) {return v.split(',') });

    // 循环push每个 符合indices索引 的值到results
    csvArr.forEach(function (v, k) {
        var _temp = [];
        indices.forEach(function (v1) {
            v[v1] && _temp.push(v[v1]);
        });

        _temp.length && results.push(_temp);
    });

    return results.join('\\n');
}


// 测试用例
console.log(csvColumns( "1,2,3\n4,5,6" , [0, 1] )) // returns "1,2\n4,5" 
console.log(csvColumns( "1,2\n3,4\n5,6" , [5, 6, 7] )) // returns "" 
console.log(csvColumns( "a,b,c,d,e\n1,2,3,4,5\nf,g,h,i,j" , [1, 3, 5, 7] )) // returns "b,d\n2,4\ng,i"

有没有更好的方式呢?

@nunnly nunnly added 难度5 and removed question labels Jan 23, 2015
@VaJoy
Copy link

VaJoy commented Feb 28, 2015

function csvColumns(csv, indices){
  var result = "",
      rawArr = csv.split("\n"),
      l = rawArr.length-1;
  rawArr.forEach(function(item,index){
      var temp, s="";
      indices.forEach(function(i){ 
          temp = item.substr(2*i,1);
          if(temp){ result+= s+temp;s=","}
      })
      result+= (index==l?"":"\\n");
  })
  return result==="\\n\\n"?"":result;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants