我有一个非常复杂的数组,需要转换为特定格式。该数组如下所示:
arr = [["name1",51,1,"code1",3],["name2",52,0,"code2",4,"code3",6],["name3",51,2,"code4",3,"code5",6,"code6",1],["name4",55,5,"code7",7,"code8",1],["name5",54,2,"code9",5,"code10",8]];
我的输出需要中的每个数组仅包含5个值-3个第一个值始终与输入中的相同。接下来的2个值应包含代码和数组其余部分中的最小值。因此,这种情况下的输出将如下所示:
output = [["name1",51,1,"code1",3],["name2",52,0,"code2",4],["name3",51,2,"code6",1],["name4",55,5,"code8",1],["name5",54,2,"code9",5]];
首先,我认为最好是使用for和if指令的循环,但是我不知道以后如何处理。
for (i=0; i<arr.length; i++) {
if (arr[i]>5) {
//dont know what to put here
}
}
我的解决方案:
arr = [
["name1",51,1,"code1",3],
["name2",52,0,"code2",4,"code3",6],
["name3",51,2,"code4",3,"code5",6,"code6",1],
["name4",55,5,"code7",7,"code8",1],
["name5",54,2,"code9",5,"code10",8]
];
function process_array(in_array) {
var output = [];
/* check each element in array */
in_array.forEach(function(sub_array){
/* store new sub array here*/
var last_sub_out = [];
var code;
var lowest_num = Number.MAX_VALUE;
/* check sub array
@value is value of sub_array
@index is index of that value.
*/
sub_array.forEach(function(value, index){
/* add first 3 values */
if(index < 3) {
last_sub_out.push( value );
return;
}
/* checking only numbers(even index: 4,6,8, ...) */
if(index % 2 == 0) {
if(value < lowest_num) {
code = sub_array[index - 1];
lowest_num = value;
}
}
});
/* add found code with lowest number */
last_sub_out.push(code, lowest_num);
output.push( last_sub_out );
/* LOG */
document.write(last_sub_out.join(', ') + "</br>");
});
return output;
}
var out = process_array(arr);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句