Perform .join on value in array of objects

前端 未结 10 1507
囚心锁ツ
囚心锁ツ 2020-11-29 15:31

If I have an array of strings, I can use the .join() method to get a single string, with each element separated by commas, like so:

[\"Joe\", \"         


        
10条回答
  •  旧巷少年郎
    2020-11-29 15:55

    not sure, but all this answers tho they work but are not optiomal since the are performing two scans and you can perform this in a single scan. Even though O(2n) is considered O(n) is always better to have a true O(n).

    const Join = (arr, separator, prop) => {
        let combined = '';
        for (var i = 0; i < arr.length; i++) {
            combined = `${combined}${arr[i][prop]}`;
            if (i + 1 < arr.length)
                combined = `${combined}${separator} `;
        }
        return combined;
    }
    

    This might look like old school, but allows me to do thig like this:

    skuCombined = Join(option.SKUs, ',', 'SkuNum');
    

提交回复
热议问题