Building a comma-separated string in JavaScript based on array element matching

I’m working with two JavaScript arrays and need help creating a specific output format.

Here are my arrays:

list1 = ["ITEM01", "ITEM02", "ITEM03", "ITEM04", "ITEM06"];
list2 = ["ITEM01", "ITEM03", "ITEM06"];

The second array always has fewer or the same number of elements as the first one.

What I want to achieve is a string that looks like this:

ITEM01,--,ITEM03,--,ITEM06

Basically, I need to go through the first array and check if each element exists in the second array. If it exists, I want to show that element. If it doesn’t exist, I want to show “–” instead.

I attempted this approach but it’s not giving me the right result:

let result = "";
for (let i = 0; i < list1.length; i++) {
    for (let j = 0; j < list2.length; j++) {
        if (list1[i] == list2[j]) {
            result += list2[j] + ",";
            continue;
        } else {
            result += "--,";
        }
    }
    continue;
}

console.log(result);

The logic seems wrong and I’m getting duplicate entries. Can someone point me in the right direction?

Your nested loop checks every element in list2 against each element in list1, so you get multiple outputs for each item. You need to break out of the inner loop when you find a match, or just use a different approach.

I’ve hit this same problem before. The includes() method is way cleaner:

let result = list1.map(item => list2.includes(item) ? item : '--').join(',');
console.log(result);

This maps over list1, checks if each element exists in list2, returns the element or ‘–’, then joins with commas. Way simpler than nested loops and fixes your duplication problem.

yeah, your inner loop keeps running thru list2 even after finding a match. just use indexOf(), like list1[i] = list2.indexOf(list1[i]) !== -1 ? list1[i] : '--' then join it. way simpler than nested loops.

Your nested loops are creating duplicates because you’re checking each list1 element against every item in list2. Skip the nested loops entirely - convert list2 to a Set first for O(1) lookups instead of O(n) array searches:

const list2Set = new Set(list2);
let result = list1.map(item => list2Set.has(item) ? item : '--').join(',');
console.log(result);

This fixes the duplicate problem and runs way faster on large datasets. I’ve used this exact pattern in production with thousands of items - works great.

This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.