Javascript programs

Array methods in JavaScript (Part 2)

Array methods in JavaScript (Part 2)

find and findIndex

array.find and array.findIndex are used to find elements satisfying a certain condition.

Syntax :

let output = arr.find(function(item) {
  // condition for which the wanted item should return true
});

The "condition function" passed into the find method is called repeatedly for each element in the array. If the function returns true, the search is stopped, the current item is returned. If no element is found, undefined is returned.

For example, we have an array of objects representing soldiers, each with name and rank properties. We want to find the first soldier with rank "LAC". Our "condition function" will be something like, function(item){ return item.rank == "LAC" or if it’s an arrow function, item => item.rank == "LAC".

Method 1

let soldiers = [
  {name: "Anna", rank: "Private"},
  {name: "Betty", rank:"LAC"},
  {name: "Caitlyn", rank: "LAC"}
  ];

let soldier = soldiers.find(function(item){ 
  return item.rank == "LAC";
});

console.log(soldier.name);       //> Betty

Method 2

let soldiers = [
  {name: "Anna", rank: "Private"},
  {name: "Betty", rank:"LAC"},
  {name: "Caitlyn", rank: "LAC"}
  ];

let soldier = soldiers.find(item => item.rank == "LAC");

console.log(soldier.name);       //> Betty

The array.findIndex method works basically the same, but returns the index of the found element instead of the element itself. The following example clarifies the difference between array.find and array.findIndex.

let soldiers = [
  {name: "Anna", rank: "Private"},
  {name: "Betty", rank:"LAC"},
  {name: "Caitlyn", rank: "SAC"}
  ];

let soldier = soldiers.find(item => item.rank == "SAC");
console.log(soldier);       //> { name: 'Caitlyn', rank: 'SAC' }


soldier = soldiers.findIndex(item => item.rank == "SAC");
console.log(soldier);       //> 2

filter

The find method looks for the first element that matches the condition of the function. If we want to find all elements that matches the condition, we use array.filter. It works the same as find, except that it returns an array of matching elements:

let soldiers = [
  {name: "Anna", rank: "Private"},
  {name: "Betty", rank:"LAC"},
  {name: "Caitlyn", rank: "LAC"}
  ];

let soldier = soldiers.filter(function(item){ 
  return item.rank == "LAC";
});

console.log(soldier);      //> [ { name: 'Betty', rank: 'LAC' }, { name: 'Caitlyn', rank: 'LAC' } ]
let soldiers = [
  {name: "Anna", rank: "Private"},
  {name: "Betty", rank:"LAC"},
  {name: "Caitlyn", rank: "LAC"}
  ];

let soldier = soldiers.filter(item => item.rank == "LAC");
console.log(soldier);       //> [ { name: 'Betty', rank: 'LAC' }, { name: 'Caitlyn', rank: 'LAC' } ]

map

The array.map method calls the function for each element of the array and returns the array of results returned by the function.

Syntax:

let result = arr.map(function(item) {
  // returns the new value inplace of each item
})

For example if we wanted to transform each element into a lowercase string we would:

let soldiers = [
  {name: "Anna", rank: "Private"},
  {name: "Betty", rank:"LAC"},
  {name: "Caitlyn", rank: "LAC"}
  ];

let soldier = soldiers.map(function(item){ 
  return item.rank.toLowerCase();
});

console.log(soldier);      //> [ 'private', 'lac', 'lac' ]

Or

let soldiers = [
  {name: "Anna", rank: "Private"},
  {name: "Betty", rank:"LAC"},
  {name: "Caitlyn", rank: "LAC"}
  ];

let soldier = soldiers.map(item => item.rank.toLowerCase());
console.log(soldier);       //> [ 'private', 'lac', 'lac' ]

sort

The method array.sort sorts an array. One thing you are going to notice about this method: it converts the elements into strings and do a lexicographic sorting. For example:

let arr = [ 0, 1, 2, 3, 4, 15, 20, 25, 30, 35, 40, 45, 50];

arr.sort();

console.log( arr );   //> [ 0, 1, 15, 2, 20, 25, 3, 30, 35, 4, 40, 45, 50 ]

Literally, all elements are converted to strings and then compared. So, the lexicographic ordering is applied and indeed "2" > "15".

To customise the sorting order, we supply a function of two arguments into the sort() method.

Lets first create the ordering function sortNumeric():

function sortNumeric(a, b) {
  if (a > b) return 1;
  if (a == b) return 0;
  if (a < b) return -1;
}

Then we pass this function into the sort method as an argument.

For example:

function sortNumeric(a, b) {
  if (a > b) return 1;
  if (a == b) return 0;
  if (a < b) return -1;
}

let arr = [ 0, 1, 2, 3, 4, 15, 20, 25, 3, 35, 4, 45, 50];

arr.sort(sortNumeric);

console.log( arr );   //> [ 0, 1, 2, 3, 3, 4, 4, 15, 20, 25, 35, 45, 50 ]

Now the array is sorted numerically. Our sortNumeric function returns 1 for the two values being compared if a is greater than b, 0 if they are equal, -1 if a is less than b. But however the comparison doesn’t have to produce 1 and -1 only, it form any positive and negative values. This allows us to shorten the sortNumeric function to:

function sortNumeric(a, b) {
  return a - b;
}

Now the function returns a positive number if a is greater than b, 0 if a and b are equal, a negative number if a is less less than b. Impressive?

function sortNumeric(a, b) {
  return a - b;
}

let arr = [ 0, 1, 2, 3, 4, 15, 20, 25, 3, 35, 4, 45, 50];

arr.sort(sortNumeric);

console.log( arr );   //> [ 0, 1, 2, 3, 3, 4, 4, 15, 20, 25, 35, 45, 50 ]

Or you can use an anonymous function:

let arr = [ 0, 1, 2, 3, 4, 15, 20, 25, 3, 35, 4, 45, 50];

arr.sort(function (a, b) { return a - b; });

console.log( arr );   //> [ 0, 1, 2, 3, 3, 4, 4, 15, 20, 25, 35, 45, 50 ]

Or, better still, you can use an arrow function:

let arr = [ 0, 1, 2, 3, 4, 15, 20, 25, 3, 35, 4, 45, 50];

arr.sort((a, b) => a - b);

console.log( arr );   //> [ 0, 1, 2, 3, 3, 4, 4, 15, 20, 25, 35, 45, 50 ]

reverse

The array.reverse method reverses the order of elements in an array.

For example:

let arr = [ 0, 1, 2, 3, 4, 15, 20, 25, 3, 35, 4, 45, 50];

arr.reverse();

console.log( arr );   //> [ 50, 45, 4, 35, 3, 25, 20, 15, 4, 3, 2, 1, 0 ]

split and join

Here’s the situation from the real life. We are writing a messaging app, and the person enters the comma-delimited list of receivers: John, Pete, Mary. But for us an array of names would be much more comfortable than a single string. How to get it?

The string.split(delim) method splits a string into an array by the delimiters delim.

For example, if we want to split a string by the comma and convert it into an array we use the following code:

let friends = "Walter, Jessy, Brandon, Skinny";

let crew = friends.split(",");

console.log( crew );   //> [ 'Walter', ' Jessy', ' Brandon', ' Skinny' ]

To use a whitespace as a delimiter:

let phrase = "The quick brown fox jumped over the lazy dogs";

let arr = phrase.split(" ");

console.log( arr );   //>  [ 'The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy','dogs' ]

This method has an optional second argument which limits the array length and ignores the rest of the elements.

let friends = "Walter, Jessy, Brandon, Skinny";

let crew = friends.split(",", 2);

console.log( crew );   //> [ 'Walter', ' Jessy' ]

More examples on the split method:

let phrase = "The quick";

let arr = phrase.split();

console.log( arr );   //>  [ 'The quick' ]
let phrase = "The quick";

let arr = phrase.split("");

console.log( arr );   //>  [ 'T', 'h', 'e', ' ', 'q', 'u', 'i', 'c', 'k' ]
let phrase = "The quick";

let arr = phrase.split(" ");

console.log( arr );   //>  [ 'The', 'quick' ]

The array.join(args) does the opposite of the split method. Which means it joins an arr into a string glued by args parameter.

For example:

let greeting = ["Good", "afternoon", "Sir."];

let str = greeting.join(" ");

console.log( str );   //>  Good afternoon Sir.
let folders = ["Home", "downloads", "New Folder"];

let path = folders.join("/");

console.log( path );   //>  Home/downloads/New Folder