3

I am new to Javascript and I was wondering is there a similar function in Javascript like C# Select(). My task is from array of people to sort the age of them and select only age of each person and print it. And this is what i come up with:

ageArraySorted = args.sort(function(person1, person2) {
    return person1.age - person2.age;
});

I sorted them and now I need only the values of age property to be printed.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Kristian Kamenov
  • 347
  • 1
  • 3
  • 12

2 Answers2

6

Without a library like linq.js the closest analog is the map method on Array;

ageArraySorted = args.sort(function(person1, person2) {
  return person1.age - person2.age;
}).map(function(item) {
  return item.age;
});
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
1

be careful with Map as a new to javascript

map does not mutate the array on which it is called (although callback, if invoked, may do so).

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]

and map was added to the ECMA-262 standard in the 5th edition;

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari Basic support (Yes) 1.5 (1.8) 9 (Yes) (Yes)

from ...https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map