Battle_Slug Battle_Slug - 5 months ago 5
Javascript Question

How to optimize the code?

I have two functions that are basically the same - they iterate over some array.
The difference is what happens inside the loop.

func1: function () {
var result = "";
for (var i = 0; i < array1.length; i++) {
result = result + array1[i].field1 + ', ';

}
if (result.length > 0) {
return result.substring(0, result.length - 2);
} else return ""
},

func2: function () {
var result = "";
for (var i = 0; i < array2.length; i++) {
result = result + array2[i].field2 + ', ';

}
if (result.length > 0) {
return result.substring(0, result.length - 2);
} else return ""
},


What is the correct way to say make it just one function, or to make both inherit some common code?
I see a solution to make it just one function and provide different parameters:

func: function (array, fieldName) {
var result = "";
for (var i = 0; i < array.length; i++) {
result = result + array[i].[fieldName] + ', ';
}
if (result.length > 0) {
return result.substring(0, result.length - 2);
} else return ""
},


But something tells me it's ugly. What is correct way to do it?

Answer

Much easier than concatenating and truncating...

func: function(array, fieldName) {
    return array.map(a => a[fieldName]).join(', ');
}
Comments