Robert Hovhannisyan
Robert Hovhannisyan

Reputation: 3335

Get access to the output array of map inside of map's callback - JS

I have a following function that iterates over array and dose some work on the item related to the array that I want to fill like this:

function fileNaming(names) {
    const result = [];

    names.forEach(name => {
        let count = 0;
        const curr = name;

        if (result.includes(name)) {
            while (result.includes(name)) {
                count++;
                name = `${curr}(${count})`;
            }
        }
        result.push(name);
    })

    return result;
}

I want to get rid of the result array and use only map for it like this:

function fileNaming(names) {
    return names.map(name => {
        let count = 0;
        const curr = name;
        // In the following 2 lines we will get error because we don't have result array anymore
        if (result.includes(name)) {
            while (result.includes(name)) {
                count++;
                name = `${curr}(${count})`;
            }
        }
        return name;
    })
}

But the problem is that I need to check something inside the outputed array but I don't know how to do it. I tried to find similar problems like this but didn't found anything, also I tried to dig up in the pollifils of map method, but everywhere was just a loop with some result array that I could get access.

Upvotes: 1

Views: 504

Answers (2)

brk
brk

Reputation: 50291

Alternatively you can use reduce & filter

function fileNamingDup(names) {
  return names.reduce((acc, curr) => {
    if (acc.includes(curr)) {
      acc.push(`${curr}(${acc.filter(elem=>elem===curr).length+1})`)
    } else {
      acc.push(curr);
    }
    return acc;
  }, []);
}
console.log(fileNamingDup(['a', 'b', 'a', 'a']));

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89204

You can use the accumulator in Array#reduce instead.

function fileNaming(names){
    return names.reduce((result, name) => {
        let count = 0;
        const curr = name;
        while(result.includes(name)){
            ++count;
            name = `${curr}${count}`;
        }
        result.push(name);
        return result;
    }, []);
}

Upvotes: 2

Related Questions