js数组转换问题

时间:2021-05-05 15:28:26

  一维数组转多维数组

    var arr=[1,2,3,4,5,6,7,8,9,10]; 

    function splitArray(arr,size){

        var result = [];
var tempArray; for(var i = 0; i < arr.length; i++){
if(i%size == 0 ){
if(tempArray){
result.push(tempArray);
}
tempArray = [];
} tempArray[tempArray.length]=arr[i];
if(i+1 == arr.length){
result.push(tempArray);
} } return result; }
console.log(splitArray(arr,3)); //[[1,2,3],[4,5,6],[7,8,9],[10]]
一维数组转多维数组并去重
var arr=[1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,7,8,9]; 

    function splitArray(arr,size){

        var result = [];
var tempArray; for(var i = 0; i < arr.length; i++){
if(i%size == 0 ){
if(tempArray){
result.push(tempArray);
}
tempArray = [];
} tempArray[tempArray.length]=arr[i];
if(i+1 == arr.length){
result.push(tempArray);
} } return result; } Array.prototype.unique = function(){ var json = {},result=[]; for(var i = 0; i < this.length; i++){
if (!json[this[i]]){
json[this[i]] = 1;
result.push(this[i]);
}
} return result; } console.log(splitArray(arr,3)); //[[1,2,3],[4,5,6],[7,8,9],[10,11,12],[1,2,3],[7,8,9]]
console.log(splitArray(arr,3).unique()); //[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
一维数组转对象数组(三维)
  var arr=[1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,7,8,9];
function splitArray(arr){ var json = {};
var arr1 = []; for(var i=0;i<arr.length;i++){
if( i%3==0 ){
json.x = arr[i];
}else if( i%3==1 ){
json.y = arr[i];
}else if( i%3==2 ){
json.z = arr[i];
arr1.push(json);
json={};
}
} return arr1; }
console.log(splitArray(arr)); //[{x:1,y:2,z:3},{x:4,y:5,z:6},{x:7,y:8,z:9},{x:10,y:11,z:12},{x:1,y:2,z:3},{x:7,y:8,z:9}]
一维数组转对象数组(三维)并去重
var arr=[1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,7,8,9];
function splitArray(arr){ var json = {};
var arr1 = []; for(var i=0;i<arr.length;i++){
if( i%3==0 ){
json.x = arr[i];
}else if( i%3==1 ){
json.y = arr[i];
}else if( i%3==2 ){
json.z = arr[i];
arr1.push(json);
json={};
}
} return arr1; } Array.prototype.unique = function(){
var json = {},arr1=[]; for(var i = 0; i < this.length; i++) {
if (!json[JSON.stringify(this[i])]) {
json[JSON.stringify(this[i])] = 1;
arr1.push(this[i]);
}
} return arr1; }
console.log(splitArray(arr)); //[{x:1,y:2,z:3},{x:4,y:5,z:6},{x:7,y:8,z:9},{x:10,y:11,z:12},{x:1,y:2,z:3},{x:7,y:8,z:9}]
console.log(splitArray(arr).unique()); //[{x:1,y:2,z:3},{x:4,y:5,z:6},{x:7,y:8,z:9},{x:10,y:11,z:12}]