2014-04-18 9 views
0

我正在研究一种检测每列的数据类型并将其加到列表顶部的算法。所以我说2D矩阵和 1)我需要检测每个元素的数据类型 2)计算每种类型矩阵列的明智总和 3)获取每个类型列的最大值明智 4)将类型从3在各自的列在javascript中检测每个列的数据类型预先计划

因此,这里的顶部是例如 enter image description here]![enter image description here

1)对于第一,我知道2层的技术。即通过jQuery

  $.each(row, function (index,item) { 
     alert(typeof(item)); //result is object instead of specific type 

2)矩阵遍历

 for (var i=0;i<data[i].length;i++) { 
     for (var j=0;j<data1.length;j++) {  
     var r = data1[j][i]; 
     if(isFinite(r) == true &&) 
     numeric++ ; 
     else {str++;} 

我知道这是不是最好的方法,但它是在给数字字符串类型的数量和

我的工作对我来说很好知道在列表顶部有一个不偏移()的前置数据。但是,仍然不确定它对我的工作方式。

任何帮助和建议。

+0

我觉得你的描述是不够的,知道你想做到完美的。请附上更多您想要的示例矩阵和结果数组。 – toshi

+0

有一个'splice'功能,您可以删除/添加特定索引上的项目。 ** [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)** –

+1

我没有得到您的数据与结果。什么是每列50和5?他们是数据的一部分吗?通过计算每种数据类型的总和,你的意思是什么?你的意思是计数每列中的项目数量?你的*“结果阵列”*中的最大值等等? – user13500

回答

0

不知道你的最终目标是什么。有人可能会说一列是字符串如果的任何的值是一个字符串,并且数字只有在所有项是数字。

小心使用变量污染全局空间。通常你会限制在封闭的范围内。

更多字符串或更多数字也必须考虑在计数等于案件。例如。五个数字和五个字符串。

下面可能是一个开始:

// Should be expanded to fully meet needs. 
function isNumber(n) { 
    return !isNaN(n + 0) /* && varius */; 
} 

// Count types of data in column. 
// Return array with one object for each column. 
function arrTypeStat(ar) { 
    var type = [], i, j; 
    // Loop by column 
    for (i = 0; i < ar[0].length; ++i) { 
     // Type-stats for column 'i' 
     type[i] = {num: 0, str: 0}; 
     // Loop rows for current column. 
     for (j = 1; j < ar.length; ++j) { 
      if (isNumber(ar[j][i])) 
       ++type[i].num; 
      else 
       ++type[i].str; 
     } 
    } 
    return type; 
} 

// Add a row after header with value equal to 'num' or 'str' depending 
// on which type is most frequent. Favoring string if count is equal. 
function arrAddColType(ar) { 
    var type = arrTypeStat(ar); 
    // Add new array as second item in 'ar' 
    // as in: add a new (empty) row. This is the row to be filled 
    // with data types. 
    ar.splice(1, 0, []); 
    // Note: 
    // Favour string over number if count is equal. 
    for (i = 0; i < type.length; ++i) { 
     ar[1][i] = type[i].num > type[i].str ? 'num' : 'str'; 
    } 
    return ar; 
} 

Sample fiddle.使用控制台,F12,查看测试结果。请注意,在此示例中,数字表示为带引号和不带引号。

// Sample array. 
var arrTest = [ 
    ['album','artist','price'], 
    [50,5,'50'],  
    [5,5,'5'], 
    ['Lateralus', 'Tool', '13'], 
    ['Ænima','Tool','12'], 
    ['10,000 days','Tool',14] 
]; 

// Test 
var test = arrAddColType(arrTest); 

// Log 
console.log(
    JSON.stringify(test) 
    .replace(/],\[/g, '],\n[')); 

产量:

[["album","artist","price"], 
["str","str","num"], 
[50,5,"50"], 
[5,5,"5"], 
["Lateralus","Tool","13"], 
["Ænima","Tool","12"], 
["10,000 days","Tool",14]] 
相关问题