[javscript][Algorism] Filter Function Question

Asked 1 years ago, Updated 1 years ago, 80 views

Hello, the code below is

Both the people and tshirts arrays are arranged in ascending order

const fp = people.filter(person => {
        For(let item of tshirts){ // Change the array value if you are looking for person in tshirt array
            if(person <= item){
                tshirts.splice(tshirts.indexOf(item),1)
                return person <= item;
            }
        }
    });
    return fp.length;

In fact, what I'm looking for is elements in the peson sequence that are less than or equal to elements in the tshirts sequence. While I was thinking about how to find it, I thought, 1. Let's make an array that fits the condition and return the length of the array, and I wrote the above code because I thought it would be best to use the filter method to make an array that fits the condition.

However, the filter function is usually most useful when returning is omitted as shown below and only an array that meets the conditions is extracted immediately.

const result = words.filter(word => word.length > 6);

In the code I made,

And so... I'm asking you a question because I think there's a better way to do it.

I understand that you have to write functions such as redox, map, and filter well to extract an array that meets the conditions. Is it best to use the filter function in this case? I'd like to ask you how to write a cleaner and more beautiful code.

Thank you for reading my question! :)

javascript filter refactoring algorithm

2022-09-22 19:02

1 Answers

There are times when techniques are important This technique may simplify the problem, though

If I look at the code, I fall into the trap of filter I think you made a code that's hard to understand unless it's an annotation.

I think it's better to have a code that's easy to understand just by looking at the code itself, even if you add a variable with an appropriate name in addition to the double for statement. Especially if you're not developing it alone.


2022-09-22 19:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.