filter data from result of json call
I am trying to do pre-processing JSON data before feed it to the dataTables. the reason is I need to separate the source data into 3 datatables. i can do it in the server-side in java but that approach is undesirable. Please don't ask why, it is just due to load balancing calculation.
type: "GET",
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log(data);
var table = $('#tbl1');
var tableUsul = $('#tbl1Terima');
var tableTolak = $('#tbl2Tolak');
table.DataTable({
"data": data.object, // i want to maipulate this
"processing": true,
"destroy": true,
"pagingType": "numbers",
"columns": [
{"data": null, "class": "rowCenter"},
{"data": "0"},
{"data": "1"},
{"data": "2"}
........
console.log(data.object) result
[
[1,"myname1","1000"],
[0,"myname2","0"],
[1,"myname5","12121"],
[1,"myname2","23455"]
]
i want to filter data.object. so in the database, the 1st column consists of 1 and 0, I want to show only 1 or only 0. i was trying to use data.filter(function(){})
but the js does not recognize the function filter.
you can try something like below.
var data = [
[1,"myname1","1000"],
[0,"myname2","0"],
[1,"myname5","12121"],
[1,"myname2","23455"]
];
var newArray = [];
for (i = 0; i < data.length; i++) {
var element = data[i];
if(element[0] == 1)
{
newArray.push(element);
}
}
console.log(newArray)
</div>
You can try the following:
let data = [[1,"myname1","1000"],[0,"myname2","0"],[1,"myname5","12121"],[1,"myname2","23455"]];
function group2DArrayDataByIndex(dataArr, groupByIndex) {
let groupedData = dataArr.reduce(function (acc, arr) {
if (Array.isArray(arr) && (arr[groupByIndex] !== undefined || arr[groupByIndex] !== null)) {
let key = arr[groupByIndex];
if (Array.isArray(acc[key])) {
acc[key].push(arr);
} else {
acc[key] = [arr];
}
}
return acc;
}, {});
return groupedData;
}
let groupByIndex = 0;
let groupedData = group2DArrayDataByIndex(data, groupByIndex);
console.log(groupedData);
console.log(groupedData[0]); //access data with only 0
console.log(groupedData[1]); //access data with only 1
What it does: This code groups the data (Array of Arrays) based on the supplied index to be used to group data. All the grouped data is stored in an object such that you can access any data without the need to group/filter again.
</div>