O
O
olya_0972018-02-19 17:57:40
JavaScript
olya_097, 2018-02-19 17:57:40

What does a, b, field mean after declaring an array of objects and why do we make 2 returns in the byField function, besides the fact that they return values?

What does a, b, field mean after declaring an array of objects and why do we make 2 returns in the field function, in addition to the fact that they return values
​​+ there is also sort and forEach below. What are they for? sort as I understand the sort method? and forEach

var users = [{
  name: "Вася",
  surname: 'Иванов',
  age: 20
}, {
  name: "Петя",
  surname: 'Чапаев',
  age: 25
}, {
  name: "Маша",
  surname: 'Медведева',
  age: 18
}];

function byField(field) {
    return function(a, b) {
      return a[field] > b[field] ? 1 : -1;
    }
  }

users.sort(byField('name'));
users.forEach(function(user) {
  alert( user.name );
});

users.sort(byField('age'));
users.forEach(function(user) {
  alert( user.name );
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2018-02-19
@Stalker_RED

This is the third time I've answered this question,
there are two functions, and each has one
sort return for sorting, right. And forEach for enumeration of the list of users.

V
Vitaly, 2018-02-19
@vitstr

The default sort array method is passed a callback function, which is returned from the byField function at startup, and which in the closure "holds" the value of field (age or name in your case).
forEach resp. iterates over the resulting array and displays an alert for each element.
According to the equipment we read:
1. Closures
2. Anonymous functions
3. Working with arrays (standard methods).
The book "Expressive JavaScript" or Ilya Kantor's course will do.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question