Sign in
Log inSign up

JavaScript: Arrays, Array-Like objects and Array Methods

Akuagwu Philemon's photo
Akuagwu Philemon
·Jun 18, 2020

filiberto-santillan-1HCb2gPk3ik-unsplash.jpg

Hello guys , So if you are new to Programming or JavasScript you must have heard about Arrays and how important they are. This Article will be talking about Arrays and some of its Methods . There will be a dedicated article talking deeply about Array Methods in JavaScript

Prerequisites

  • JavaScript as a language
  • Basic knowledge of Programming
  • willingness to Learn

WHAT IS AN ARRAY

The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

  • For Example : var arr = ['a', 'b' ,'c']

What Array-Like Objects

Some objects in JavaScript look like an array, but they aren't one. That usually means that they have indexed access and a length property, but none of the array methods. Examples include the special variable arguments, DOM node lists, and strings

  • var arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };

Convert Array-like Objects to Arrays in ES6

  • Using Array.from() const realArray = Array.from(arrayLike);
  • Spread Operator const realArray = [...arrayLikeObject]

Now What are Array Methods and how can we use them

Array Methods (like every method of an Class) are special functions associated with arrays that can be use to Iterate, manipulate and/or mutate the array and its values. They include

  • push
  • pop
  • unshift
  • shift
  • forEach
  • map
  • reduce
  • filter
  • find
  • sort
  • entries
  • concat
  • some
  • every
  • indexOf
  • findIndex

Push ( array method )

The Array.prototype.push() method is used to add elements to an array to the last .for example

const arr = [ 'a', 'b', 'c' ]

  • console.log(arr) // [ 'a', 'b', 'c' ]
  • arr.push('d')
  • console.log(arr) // [ 'a', 'b', 'c' , 'd' ]

Pop ( array method )

The Array.prototype.pop() method is used to remove element from an array from last

const arr = [ 'a', 'b', 'c' ]

  • console.log(arr) // [ 'a', 'b', 'c' ]
  • arr.pop()
  • console.log(arr) // [ 'a', 'b' ]

Shift( array method )

The Array.prototype.shift() method is used to remove element from an array from the first element

const arr = [ 'a', 'b', 'c' ]

  • console.log(arr) // [ 'a', 'b', 'c' ]
  • arr.shift()
  • console.log(arr) // [ 'b', 'c' ]

Unshift ( array method )

The Array.prototype.unshift() method is used to add element to an array from the first

const arr = [ 'a', 'b', 'c' ]

  • console.log(arr) // [ 'a', 'b', 'c' ]
  • arr.shift('d')
  • console.log(arr) // [ 'd', 'a', 'b', 'c' ]

forEach

The Array.prototype.forEach is simply used to iterate through an array elements with out mutating . (changing the values of the array ). It is similar to iterating with a for loop.

const arr = [ 'a', 'b', 'c' ]

  • console.log(arr) // [ 'a', 'b', 'c' ]
  • arr.forEach( element => console.log(element) ) // a b c

Map ( Higher order Function )

The Array.prototype.map() is used to also iterate through the values of an array to mutate the values

const arr = [ 1, 2, 3 ]

  • console.log(arr) // [ 1, 2, 3 ]
  • arr.map( element => element + 1 )
  • console.log(arr) // [ 2, 3, 4 ]

Reduce

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

const arr =[1, 2, 3, 4].

  • console.log(arr) // [ 1, 2, 3 , 4]
  • arr.reduce(function(a, b) { return a + b; }); // → 10

Filter

As the name implies it simply filters an array based on a stipulated condition and returns the filtered array as a new value without mutating the array itself.

// Suppose we want to get all odd number in an array:

  • var numbers = [5, 32, 43, 4];
  • var odd = numbers.filter(function(n) { return n % 2 !== 0; });
  • Version ≥ 6 let odd = numbers.filter(n => n % 2 !== 0); // can be shortened to (n => n % 2)
  • odd would contain the following array: [5, 43].

Find

As the Name implies it simply search for the first element in an array that meets the condition you give

let people = [ { name: "bob" }, { name: "john" } ];

  • let bob = people.find(person => person.name === "bob"); // Or, more verbose
  • let bob = people.find(function(person) { return person.name === "bob"; });

Sort

The .sort() method sorts the elements of an array. The default method will sort the array according to string

Unicode code points. To sort an array numerically the .sort() method needs to have a compareFunction passed to it.

Note: The .sort() method is impure. .sort() will sort the array in-place, i.e., instead of creating a sorted copy of the original array, it will re-order the original array and return it.

Default Sort

Sorts the array in UNICODE order.

['s', 't', 'a', 34, 'K', 'o', 'v', 'E', 'r', '2', '4', 'o', 'W', -1, '-4'].sort();

Results in:

[-1, '-4', '2', 34, '4', 'E', 'K', 'W', 'a', 'l', 'o', 'o', 'r', 's', 't', 'v']

Note: The uppercase characters have moved above lowercase. The array is not in alphabetical order, and numbers are not in numerical order. Alphabetical Sort

['s', 't', 'a', 'c', 'K', 'o', 'v', 'E', 'r', 'f', 'l', 'W', '2', '1'].sort((a, b) => { return a.localeCompare(b); });

Results in:

['1', '2', 'a', 'c', 'E', 'f', 'K', 'l', 'o', 'r', 's', 't', 'v', 'W']

Note: The above sort will throw an error if any array items are not a string. If you know that the array may contain items that are not strings use the safe version below.

['s', 't', 'a', 'c', 'K', 1, 'v', 'E', 'r', 'f', 'l', 'o', 'W'].sort((a, b) => { return a.toString().localeCompare(b); });

String sorting by length (longest first)

["zebras", "dogs", "elephants", "penguins"].sort(function(a, b) { return b.length - a.length; });

Results in

["elephants", "penguins", "zebras", "dogs"];

String sorting by length (shortest first)

["zebras", "dogs", "elephants", "penguins"].sort(function(a, b) { return a.length - b.length; });

Results in

["dogs", "zebras", "penguins", "elephants"]; Numerical Sort (ascending) [100, 1000, 10, 10000, 1].sort(function(a, b) { return a - b; });

Results in:

[1, 10, 100, 1000, 10000]

Numerical Sort (descending)

[100, 1000, 10, 10000, 1].sort(function(a, b) { return b - a; }); Results in:

[10000, 1000, 100, 10, 1] Sorting array by even and odd numbers [10, 21, 4, 15, 7, 99, 0, 12].sort(function(a, b) { return (a & 1) - (b & 1) || a - b; }); Results in: [0, 4, 10, 12, 7, 15, 21, 99]

Date Sort (descending)

var dates = [ new Date(2007, 11, 10), new Date(2014, 2, 21), new Date(2009, 6, 11), new Date(2016, 7, 23) ];

  • dates.sort(function(a, b) {
  • if (a > b) return -1;
  • if (a < b) return 1; return 0; }); // the date objects can also sort by its difference // the same way that numbers array is sorting
  • dates.sort(function(a, b) { return b-a; });
  • Results in: [ "Tue Aug 23 2016 00:00:00 GMT-0600 (MDT)", "Fri Mar 21 2014 00:00:00 GMT-0600 (MDT)", "Sat Jul 11 2009 00:00:00 GMT-0600 (MDT)", "Mon Dec 10 2007 00:00:00 GMT-0700 (MST)" ]

Entries

The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the array.

var letters = ['a','b','c'];

  • for(const[index,element] of letters.entries()){ console.log(index,element); }
  • result 0 "a" 1 "b" 2 "c"

Concat

The concat() method is used to concatenate arrays to become one array

Two Arrays

  • var array1 = [1, 2];
  • var array2 = [3, 4, 5];

    Version ≥ 3

    var array3 = array1.concat(array2); // returns a new array

    Version ≥ 6

  • var array3 = [...array1, ...array2]

Some

The Some() method returns a Boolean (true / false) . It returns true if any array element meets the condition you give

var arr = [1, 2, 3, 4]

arr.some(x => x > 2)

  • returns true // because one or more elements in the array are greater than 2

    arr.some( x => x > 8 ) // false

  • because none of the elements in the array have a value higher than 8

Every

The every() method returns a Boolean (true / false) . It returns true if all array element meets the condition you give

var arr = [1, 2, 3, 4]

arr.every(x => x > 0) returns true // because all elements in the array are greater than 0

arr.every( x => x > 2 ) // false

  • because none of the elements in the array have a value higher than 8

Conclusion

Thank you guys for reading my Article. Please Look out for more and Follow me on Twitter @Ace1Philz and HashNode so that you can vote and make request for the next topic you will like me to write on (Polls will be raised on Sundays) you can decide if You want to see a more