Reputation: 818
Example view of my arr.
There need to concat deepest objects,
for example have 2 arrays [{id1:color:grey}] [{id4:color:grey},{id8:color:grey}]
in result need be this: [{id1:color:grey},{id4:color:grey},{id8:color:grey}]
try do something this but no idea how to concat, I don't know how much arrays can be
var kkk = [];
for (var i=0; i < arrData.length;i++) {
var his = arrData[i][1];
for(var k=0; k < his.length; k++) {
console.log(his[0])
}
}
what I must do in loop? and loop is correct?
My object :
Array[2]
0:"th"
1:Array[2]
0:Array[1] //this need concat
1:Array[1] //this need concat
["th"
,[[[{"id":4,"color":"grey"},
{"id":5,"color":"grey"},
{"id":6,"color":"grey"},
{"id":7,"color":"grey"},
{"id":8,"color":"grey"},
{"id":9,"color":"grey"},
{"id":10,"color":"grey"},
{"id":11,"color":"grey"},{"id":12,"color":"grey"}]],
[[{"id":19,"color":"grey"},{"id":20,"color":"grey"},{"id":21,"color":"grey"}
]]]]
Upvotes: 0
Views: 185
Reputation: 27247
function flatten(arr) {
if (Array.isArray(arr)) return
Array.prototype.concat.apply([], arr.map(flatten));
return arr;
}
This is the basic recursive solution for flatten.
Upvotes: 0
Reputation: 9412
You can flatten the array and then concatenate results into the array.
I used code from one of my repos.
var arr = [[[{color : "red", id : 1}]],[{color : "green", id : 2}],[[[{color : "yellow", id : 3}]]],[{color : "blue", id : 4}]];
const __flattenReducer = (result,value,valueIndex,arr)=>{
if(value instanceof Array){
return value.reduce(__flattenReducer,result);
}else{
result.push(value);
return result;
}
};
const flatten = function(arr){
if(arr instanceof Array){
return Array.prototype.reduce.apply(arr,[__flattenReducer,[]]);
}else{
throw new TypeError('Expected an array');
}
}
console.log(flatten(arr))
Upvotes: 1