JS Functional how to start [closed]

0

Hello, could anyone give me a strength, how to improve this 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'
  }
}
    
asked by anonymous 25.01.2017 / 20:51

1 answer

0

Well, from what I understand you want to check if a property of all items in the array are the same and return the result, see if that fits 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 receives the array, the key to be compared, and a return function (callback) , then I make a loop to compare the elements of the array and call the function of callback with the answer.

    
26.01.2017 / 14:22