0
\$\begingroup\$

This function is working fine but I'm looking for any better alternative:

function formate(array) {
    var formattedArray = [];
    var count = array.length;

    for (var i = 0; i < count; i++) {
        formattedArray.push({
            all: array[i].all ? array[i].all.split(',') : [],
            any: array[i].any ? array[i].any.split(',') : [],
            not: array[i].not ? array[i].not.split(',') : [],
        });
    }

    return formattedArray;  
}

Input:

[{all: "one,two", any: "three,four", not: ""},{all: "five,six", any: "", not: "seven"}]

Output:

[{all: ["one", "two"], any: ["three", "four"], not: []}, {all: ["five", "six"], any: [], not: ["seven"]}]
\$\endgroup\$
  • 2
    \$\begingroup\$ I am not sure how it is not efficient? Do you see performance problems? You could switch to map but running jsperf tests might determine if it is better or not. \$\endgroup\$ – epascarello Dec 6 '17 at 16:04
2
\$\begingroup\$
const formate = array => array.map(({all, any, not}) => ({all: all.split(","), any: any.split(","), not: not.split(",")}));

With empty arrays:

const formate = array => array.map(({all, any, not}) => ({all: all?all.split(","):[], any: any?any.split(","):[], not: not?not.split(","):[]}));
\$\endgroup\$
  • \$\begingroup\$ I need to avoid that empty string but your code producing something like this '[{all: ["one", "two"], any: ["three", "four"], not: [""]}, {all: ["five", "six"], any: [""], not: ["seven"]}]' \$\endgroup\$ – Arjun Kariyadan Dec 6 '17 at 16:18
  • \$\begingroup\$ How to do that with the above code. Can you help me? \$\endgroup\$ – Arjun Kariyadan Dec 6 '17 at 16:21
  • \$\begingroup\$ @arjun shure, just include the ternary you used. \$\endgroup\$ – Jonas Wilms Dec 6 '17 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy