Convert Multi-dimensional Array Into Single Array (javascript)
I have an object array (coming from an XLSX.js parser, so its length and contents vary) representing grants that have been given to projects. Simplified, it looks something like th
Solution 1:
Would this be an idea?
var grants = [
{ id: "p_1", location: "loc_1", type: "A", funds: "5000" },
{ id: "p_2", location: "loc_2", type: "B", funds: "2000" },
{ id: "p_3", location: "loc_3", type: "C", funds: "500" },
{ id: "p_2", location: "_ibid", type: "D", funds: "1000" },
{ id: "p_2", location: "_ibid", type: "E", funds: "3000" }
];
var joined = [];
// map and push to joined
grants.map(
function (v) {
if (!(v.idinthis)) {
this[v.id] = v;
joined.push(v);
} else {
var current = this[v.id];
current.type = [v.type].concat(current.type);
current.funds = [v.funds].concat(current.funds);
}
}, {}
);
// show itdocument.querySelector('#result').textContent =
JSON.stringify(joined, null, ' ');
<preid="result"></pre>
Solution 2:
You can just change these lines:
res[value.id].type = [res[value.id].type, value.type];
res[value.id].funds = [res[value.id].funds, value.funds];
To this:
Array.isArray(res[value.id].type) ? res[value.id].type.push(value.type) : res[value.id].type = [res[value.id].type, value.type];
Array.isArray(res[value.id].funds) ? res[value.id].funds.push(value.funds) : res[value.id].funds = [res[value.id].funds, value.funds];
Solution 3:
This will do:
var tempArr = [];
var result = [];
for(i in grants){
var rowObj = grants[i];
var idPos = tempArr.indexOf(rowObj.id);
if(idPos > -1){
result[idPos].type.push(rowObj.type);
result[idPos].funds.push(rowObj.funds);
}else{
tempArr.push(rowObj.id);
rowObj.type = [rowObj.type]
rowObj.funds = [rowObj.funds]
result.push(rowObj);
}
}
console.log(result);
Solution 4:
I propose this solution.
It features a look up, if the index exist in the project array, if so it pushes the type and funds if not then the type and funds properties are changed to array with the value as first element.
var grants = [
{ id: "p_1", location: "loc_1", type: "A", funds: "5000" },
{ id: "p_2", location: "loc_2", type: "B", funds: "2000" },
{ id: "p_3", location: "loc_3", type: "C", funds: "500" },
{ id: "p_2", location: "_ibid", type: "D", funds: "1000" },
{ id: "p_2", location: "_ibid", type: "E", funds: "3000" }
],
project = [];
grants.forEach(function (a) {
!project.some(function (b, i) {
if (a.id === b.id) {
project[i].type.push(a.type);
project[i].funds.push(a.funds);
returntrue;
}
}) && project.push({ id: a.id, location: a.location, type: [a.type], funds: [a.funds] });
});
document.write('<pre>' + JSON.stringify(project, 0, 4) + '</pre>');
Post a Comment for "Convert Multi-dimensional Array Into Single Array (javascript)"