I have the following array data and i am calculating the number of records that match using the includes criteria.
var final =
[
[
"61131",
"NISSAN",
"BOLTON",
"MAINT"
],
[
"61132",
"NISSAN",
"BOLTON",
"MAINT"
],
[
"61133",
"TOYOTA",
"STOCKPORT",
"STORED"
],
[
"61134",
"TOYOTA",
"STOCKPORT",
"MAINT"
],
[
"61135",
"NISSAN",
"STOCKPORT",
"MAINT"
],
[
"61136",
"NISSAN",
null,
null
]
]
and the code is this one :
var obj = {};
var num1 = 0;
var num2 = 0;
for (var i=0; i<final.length; i++){
if(final[i].join(';').includes('BOLTON') && final[i].join(';').includes('MAINT') && final[i].join(';').includes('NISSAN')) {
num1++;
}
}
for (var i=0; i<final.length; i++){
if(final[i].join(';').includes('STOCKPORT') && final[i].join(';').includes('STORED') && final[i].join(';').includes('TOYOTA')) {
num2++;
}
}
obj['BOLTON_MAINT_NISSAN'] = num1
obj['STOCKPORT_STORED_TOYOTA'] = num2
console.log(obj)
output
{ "BOLTON_MAINT_NISSAN": 2, "STOCKPORT_STORED_TOYOTA": 1}
I am getting the desired result, is there a more efficient way of writing the above code that is minimal ?
final[i].join(';')always returns the same thing, but it's being run six (6) times per element in your array.NissanorToyotaalways appears in the second position, etc. You probably don't need to use.joinat all