1

I want to know if we can call an extern function/method inside reduce iteration ?

Inside mainFunction i'm using reduce on array and i want to call an extern function formatDate inside my reduce iteration, is this good approach to do it ? if yes then how ?

private mainFunction() : {
  
  let v_arrayGroup:string[]=[];
  
  myArray.reduce(function (res, value) {

        let v_key = value.firstVar;
        
        if (!res[v_key]) {

          res[v_key] = {
            firstVar: value.firstVar,
            NbrKo: 0,
            sndVar: this.formatDate(value.sndVar)
          };
          
          v_arrayGroup.push(res[v_key]);
        }

        res[v_key].NbrKo++;
        return res;
      }, {});
      
      v_finalArray = v_arrayGroup;
      
    }
      
     private formatDate=(p_date:Date)=> {
          let addZeroToLoneFigure = (n) => n.toString().length === 1 ? '0' + n : n.toString();
          let _dateReturn = 'DD/MM/YYYY';
      
         _dateReturn=  _dateReturn.replace("DD", addZeroToLoneFigure(p_date.getDate()));
      
          _dateReturn= _dateReturn.replace("MM", addZeroToLoneFigure(p_date.getMonth() + 1));
      
         _dateReturn=  _dateReturn.replace("YYYY", addZeroToLoneFigure(p_date.getFullYear()));
         
          return _dateReturn;
      }
oox-hmz
  • 13
  • 5
  • Yes you can, as long as that function is available in the surrounding scope (note, your usage of [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) is incorrect here as you're not returning anything, consider using a for loop, or `.forEach`) – Nick Parsons Oct 09 '20 at 10:18
  • Hello Nick, yes i know that but when you try to do it you will not be able to call an extern function that's why i'm asking if there is a way to do it – oox-hmz Oct 09 '20 at 12:00
  • What makes you say that you're not able to call the external function? Are you getting any errors? Your code should work provided that you're using reduce correctly – Nick Parsons Oct 09 '20 at 12:02
  • Because it's not working bro, i'm gonna edit my question and put all code so you can see, may be i got a syntax problem or something – oox-hmz Oct 09 '20 at 12:32
  • Change `function (res, value) {` to an arrow function so that the `this` doesn't get bound to the global object but rather stays as your object – Nick Parsons Oct 09 '20 at 12:43
  • That's work ! thank's Nick, can't vote for your comment, you can put answer so i accept it like a solution or i'll do it – oox-hmz Oct 09 '20 at 13:16
  • this question is actually a duplicate of another question, I'll add it to your question so others can see it - happy coding – Nick Parsons Oct 09 '20 at 13:17

0 Answers0