JS Functional how to start

Asked

Viewed 79 times

0

Hello, someone could give me a strength, how to improve it for functional js

for (var i = 0; i < newArr.length; i++) {
  var dtAlterar = newArr[1].dtAlterar;
  if(newArr[i].dtAlterar != dtAlterar){
    var igual = 'diferente'
    break;
  }else{
    var igual = 'igual'
  }
}
  • 1

    What do you want to do? Turn it into a function? You can give an example of the application you want to do?

  • I do not know if it is the case to insert this tip in the comment :p, but it has an API for several languages (including js) that I am studying that is aimed at functional programming. Reactivex

  • What is the purpose of this code? It compares the property dtAlterar of all elements of the array with the second element and do nothing with that result? If you explain it better it will be easier to help

  • Then, I need to compare array items, if they are equal returns the same, if value is different it is returning different

  • I found Uma Linda solucao para nossso problemas rsrs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

1 answer

0


Well, from what I understand you want to check if a property of all the items in the array are equal and return the result, see if this suits you:

function compareArrayValues(arr, field, callback) {
  var response = 'Igual';
  
  for(x in arr) {
    if(arr[x][field] != arr[0][field]) {
      response = 'Diferente';
      break;
    }
  }
  
  callback(response);
}

var arr = [
  { nome: 'abc' },
  { nome: 'abc' },
  { nome: 'abc' }
];

compareArrayValues(arr, 'nome', function(response) {
  console.log(response);  
});

What I do is define a function that takes the array, the key to be compared, and a return function (callback), then I make a loop to compare array elements and call the function callback with the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.