I have some code which is working, but I would be interested if anyone could review it and tell me if there is a more efficient way of achieving my goal.
I receive input from a data source as an array such as ["Y","Y",,"Y","Y",,"Y"].
The values relate to investment fund names and I am outputting a string such as "Balanced, Cash, High Growth, Moderate and Growth options".
If there is only one value populated with "Y" the string could be "Conservative option".
If there are two values, the string could be "Conservative and Cash options".
For more than two values, the string could be "Conservative, Cash and Moderate options".
I know that the order of the values will always be the same, eg the first value will always be the Balanced option. Here is the code:
// balanced, cash, high growth, moderate and growth var params = ["Y","Y",,"Y","Y",,"Y"]; getString(params) function getString(values) { // map for the values var fundMap = { 0: "Balanced", 1: "Cash", 2: "Conservative", 3: "High Growth", 4: "Moderate", 5: "Shares", 6: "Growth" } var fundArray = []; // get fund names from map and push to array for (var i = 0; i < values.length; i++) { if (values[i] == "Y") { fundArray.push(fundMap[i]); } } console.log(fundArray); var fundString = ""; if (fundArray.length == 1) { fundString = fundArray + " option"; } else if (fundArray.length == 2) { fundString = fundArray[0] + " and " + fundArray[1] + " options"; } else { for (var i = 0; i < fundArray.length -2; i++) { fundString = fundString + fundArray[i] + ", "; } fundString = fundString + fundArray[fundArray.length -2] + " and "; fundString = fundString + fundArray[fundArray.length -1] + " options"; } console.log(fundString); }
I would love to know if there is a more efficient or just a neater way of writing this code please.
Thank you!
var params = ["Y","Y",,"Y","Y",,"Y"];
Sparse arrays are almost always a mistake, consider fixing the data source to use a well-formatted array instead, if possible\$\endgroup\$