I have trouble with my code. i want display record sum jk = P
and jk = L
const JK = ["L", "P"];
const data = [{
"name": "Faris",
"jk": "L"
}, {
"name": "Nanda",
"jk": "P"
}, {
"name": "Ani",
"jk": "P"
}]
var b = []
for (var a = 0; a < JK.length; a ) {
for (var i = 0; i < data.length; i ) {
if (data[i].jk == JK[a]) b.push(data[a] = 1)
}
}
console.log(b);
I want b = [1, 2]
CodePudding user response:
b.push(data[a] = 1)
doesn't work here. You need to set the array elements somewhere which is best done at the start, and then you can add to them. Try creating an array of 0s with the length of JK
var b = Array(JK.length).fill(0)
and then you can add to that array with your given index
if (data[i].jk == JK[a]) { b[a] = 1 }
CodePudding user response:
Notes
OK, I think I understand what you are trying to do. You want to loop through a data list and count how many "jk" types exist.
JS
const dataList = [
{ "name": "Faris", "jk": "L" },
{ "name": "Nanda", "jk": "P" },
{ "name": "Ani", "jk": "P" }
];
const counts = {};
const selectKey = 'jk';
// Loop through each item in dataList
for ( const item of dataList ){
// Skip item if it is missing or missing the needed key
if ( !item || !item[ selectKey ] ) continue;
// initialize counts if first time accessing
if ( !counts[ item[ selectKey ] ] ) counts[ item[ selectKey ] ] = 0;
// increment key count
counts[ item[ selectKey ] ] ;
}
console.log( 'counts object', counts ); // Result = {L: 1, P: 2}
console.log( 'counts array', [ counts.L, counts.P ] ); // Result = [ 1, 2 ]