FCC Intermediate Algorithm Drop it

Source: Internet
Author: User

Drop it lets us discard the elements of the array (arr), starting from the left, until the callback function return true stops.

The second argument, which func is a function. To test the first element of the array, if it returns Fasle, the element is thrown from the array (note: The array has been changed at this point), the first element of the array continues to be tested, and if Fasle is returned, the throw continues until it returns true.

The remainder of the array is returned, and an empty array is returned if there are no remaining ones.

Arguments Objectarray.shift () Array.slice () Idea: (1) Get the length of the array first (the length of the array is changed in the following loop); (2) design A For loop based on the length of the array (not called traversal) ; (3) Gets the first element of the current array (where the shift operation has actually changed the array), and if the Func function is met, the first element that was just taken away is returned to the array, so that the ARR array will not change if the first element that meets the Func function is dozen (a minus, One adds back), and finally returns an array of arr; knowledge Point: (1) the Array.shift () method from the array DeleteThe first element, and returns the value of the element. This method changes the length of the array. (2) The Array.unshift () method adds one or more elements to the beginning of the array and returns the length of the new array. Code:
1 functionDrop (arr, func) {2   //Drop them elements.3 varL=arr.length;4    for(vari=0;i<l;i++){5     varFir=Arr.shift ();6    if(func (FIR)) {7 Arr.unshift (FIR); 8    }9   }Ten  One   returnarr; A } -  -Drop ([1, 2, 3, 4,5],function(n) {returnn > 4;});

FCC Intermediate Algorithm Drop it

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.