2

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.

2
  • 1
    At a quick glance, the reduce method may be a better option for such a problem because then you'll have the accumulator that you can use for the required comparisons. (If I am not missing anything) Commented Jul 15, 2021 at 14:45
  • @OrkunTuzel yeah, that was the point, thank you :) Commented Jul 15, 2021 at 15:04

2 Answers 2

3

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;
    }, []);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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']));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.