This is my first time posting on stack overflow so if someone can advise if there is more info needed to help. I am also super new to JS/Programming
I a trying to get the program to pull out the most common word from an array.
function checkData(array) {
if (array.length == 0) return null;
const checkingMap = {};
let maxType = "",
maxCount = 1;
for (let j = 0; j < array.length; j++) {
for (let i = 0; i < array.length; i++) {
let element = array[i];
if (checkingMap[element] == null) {
checkingMap[element] = 1;
} else {
checkingMap[element]++;
}
if (checkingMap[element] > maxCount) {
maxType = element;
maxCount = checkingMap[element];
}
}
}
console.log(maxType);
}
There could be an issue with the data source? I have included the data file below:
const dataCheck = require("./medicineData");
const patients = [
{
name: "Charlie",
age: "42",
allowedMedicine: ["type-a", "type-b", "type-c"],
},
{
name: "Veronica",
age: "33",
allowedMedicine: ["type-a", "type-c"],
},
{
name: "Spencer",
age: "57",
allowedMedicine: ["type-e"],
},
{
name: "Wolfram",
age: "74",
allowedMedicine: ["type-d", "type-a"],
},
{
name: "Jennifer",
age: "22",
allowedMedicine: ["type-a", "type-c"],
},
];
let newArray = [];
let finalMedicineList = [];
function arrangeData() {
for (let i = 0; i < patients.length; i++) {
newArray.push(patients[i].allowedMedicine);
}
const mergedArray = newArray.flat(1);
finalMedicineList.push(mergedArray);
const array = finalMedicineList;
dataCheck.checkData(finalMedicineList);
}
arrangeData();
2
Answers
you are declaring const array as local scope that’s why you are not able to access array for access array you should simply replace const array with let array and declare it out of function with let newArray = [] ,let finalMedicineList = [].
otherwise if you don’t want to declare array as let then you can declar const a with let newArray = [] ,let finalMedicineList = []. and push finalMedicineList in array
like this
and you also need to change your upper part code you doesn’t need any nested for loop remove the j loop and your code will be look like this:
Just make sure you return your result rather than console logging it: