Activity Forums Salesforce® Discussions What reduce(function) will do in component.find() in Salesforce Lightning?

  • Prachi

    Member
    August 24, 2018 at 1:45 pm

    Hello Anjali,

    Reduce() - The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

    In your code , it takes a function as input and applies that on the component.find(‘contactField’) and returns the output.

    Thanks.

  • Anurag

    Member
    August 24, 2018 at 1:46 pm

    Hi  Anjali,

    reduce function is part of array prototype javascript object. It takes a function as input and applies that on the array and returns the output.

    The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

    var total = [0, 1, 2, 3].reduce(function(sum, value) {
    return sum + value;
    }, 0);
    // total is 6

  • Parul

    Member
    September 20, 2018 at 6:07 pm

    Hi,

    reduce() is javaScript array method,  actually this is the syntax of this method :

    syntax : array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

    In your scenario it will return field value from given field in InpCmp.

  • shariq

    Member
    September 20, 2018 at 11:06 pm

    Hi,

    Example of reduce()

    const array1 = [1, 2, 3, 4];
    const reducer = (accumulator, currentValue) => accumulator + currentValue;

    // 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer));
    // expected output: 10

    // 5 + 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer, 5));
    // expected output: 15

    Hope this helps.

  • Parul

    Member
    September 21, 2018 at 3:52 am

    How to use in Lightnign coe snippet:

    // If there are more than 1 fields
    if(contactFields.length!=undefined) {
    // Iterating all the fields
    var allValid = contactFields.reduce(function (validSoFar, inputCmp) {
    // Show help message if single field is invalid
    inputCmp.showHelpMessageIfInvalid();
    // return whether all fields are valid or not
    return validSoFar && inputCmp.get('v.validity').valid;
    }, true);

     

    Thanks

Log In to reply.

Popular Salesforce Blogs