20 Fastest Methods to Easily identify Array's Operation in JavaScript

20 Fastest Methods to Easily identify Array's Operation in JavaScript

In this post, I'll show you 20 Methods to Get to Know JavaScript Array Operations

Methods to Get to Know JavaScript Array Operations

For example, Let’s create an Array.

var foods =  ["🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©"];
1. Filter

The filter() method creates a new array with elements that return true from the callback function.

var foods =  ["🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©"];

var vegFoods = foods.filter( (food) => isVeg(food) );

vegFoods; ["🍎", "🍊", "πŸ•"];
2. lastIndexOf

First last index of a given element in the Array, if it is not present, it returns -1.

var foods = ["🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©", "🍎"];

foods.lastIndexOf('🍎'); // 5

foods.lastIndexOf('πŸ”'); // -1
3. Length

Returns the number of an element of the Array.

foods.length; // 5

Tip: We can change the length property to delete elements.

foods.length = 0;

foods; // []
4. Push

Add an element to the end of an Array.

var foods =  ["🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©"];

foods.push('πŸ‡');

foods; // ["🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©", "πŸ‡"]

Tip: Use push with the spread operator (…) as an alternative to the concat method.

var numbers = [1,2,3,4,5];

var num2 = [6,7,8,9,10];

numbers.push(...num2);
5. Unshift

Add an element to the beginning of an Array.

var foods =  ["🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©"];

foods.unshift('πŸ‡');

foods; // ["πŸ‡", "🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©"]

Tip: Use unshift with the spread operator (…) to concat elements at the beginning.

var numbers = [1,2,3,4,5];

var num2 = [6,7,8,9,10];

numbers.unshift(...num2);
6. Pop

Removes the last element of the array.

var foods =  ["🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©"];

foods.pop();  // "πŸ₯©"

foods; // ["🍎", "🍊", "πŸ—", "πŸ•"]

Tip: We can use the pop method in stack implementation.

7. Shift

Remove the first element of the array.

var foods =  ["🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©"];

foods.shift();  // "🍎"

foods; // ["🍊", "πŸ—", "πŸ•", "πŸ₯©"]

Tip: We can use the shift method in dequeue operations on Queue implementation.

8. Join

Joins the elements of Array to String.

var foods =  ["🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©"];

var joinedFood = foods.join(); // "🍎,🍊,πŸ—,πŸ•,πŸ₯©";

var joinedFood1 = foods.join('--'); // "🍎--🍊--πŸ—--πŸ•--πŸ₯©"

Tip: Use as an alternative to string concatenation.

var arr = ['J','a','v', 'a'];

var str = '';

// without join

for(let i = 0, len = arr.length; i < len ; i++) {

     str += arr[i];
		 
}

// with join

str = arr.join(''); // Java
9. Concat

Concat an Array with arguments.

var array = [1,2,3,4,5];

var newArray =  array.concat(1,2,3, [12,12,34], undefined, null);

newArray; // [1, 2, 3, 4, 5, 1, 2, 3, 12, 12, 34, undefined, null]
10. Reverse

Reverse the elements of the array.

var foods =  ["🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©"];

foods.reverse();

foods; // ["πŸ₯©", "πŸ•", "πŸ—", "🍊", "🍎"]

Tip: Reversing string.

var str = "Anitha";

var strArray = [...str].reverse().join('');
11. indexOf

First index of a given element in the Array, if it is not present, it returns -1.

var foods = ["🍎", "🍊", "πŸ—", "πŸ•", "πŸ₯©", "🍎"];

foods.indexOf('🍎'); // 0

foods.indexOf('πŸ”'); // -1
12. Some

Checks if any of the elements return true from the callback function.

var num = [1,2,3,4,10, 12];

num.some(n => n > 10); // true

num.some(n => n > 100); // false
13. Every

Check if all of the elements return true from the callback function.

var num = [1,2,3,4,10, 12];

num.every(n => n > 10); // false

num.every(n => n > 0); // true
14. Sort

Sort the elements of the array. By default, it sorts based on char code. We can also pass our sort function.

var arr = ['b', 'c', 'd', 'e'];

arr.sort(); // ["b", "c", "d", "e"]

// custom sort

var arr = [1,2,3,4,5, 11 ];

arr.sort( (a, b) => a-b ); // [1, 2, 3, 4, 5, 11]

Be careful using the sort method, because it sorts based on char code, in which β€œ11" < β€œ2”.

var arr = [1,2,3,4,5, 11 ];

arr.sort();  [1, 11, 2, 3, 4, 5]

Tip: Shuffle an Array with sort.

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

arr.sort( () => Math.random() - 0.5);
15. Reduce

The reduce() method executes a reducer function (which you provide) on each element of the array, resulting in a single output value.

Example one:

var apples = ["🍎", "🍎"];

var juice = πŸ§ƒ ;  // think as empty can 

function makeJuice(juice, fruit) {

    let fruitMix = grind(fruit);
		
    return fruitMix + juice;
		
}

apples.reduce( makeJuice , juice);

Example two:

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

var result = 0;

function add(res, currentNum) {
   return res + currentNum;
	 
}

arr.reduce(add, result);
16. ReduceRight

Similar to reduce but elements are passed to the callback function from right to left.

var array = [1,2,3,4,5];

function sum(result, num) {

   console.log(num);
	 
   return result + num;
	 
}

var result = 0;

array.reduce(sum, result);

// go from left to right i.e., 1,2,3,4,5

array.reduceRight(sum, result);

// go from right to left i.r., 5,4,3,2,1
17. Map

Creates a new Array from the value returned by the callback function, which is executed for every element of the Array.

var numbers = [1,2,3,4,5];

function double(num) {
   return num * num;
}

var doubledNumbers = numbers.map(double) 
18. Splice

The splice() method will remove n number of elements from the specific index and also inserts the elements.

var array = [1,2,4,5];

array.splice(2, 0, 3); //insert 3 at index 2

array;  // [1,2,3,4,5]

array.splice(2, 1, 30);//remove 1 item from index 2 and insert 30

array; // [1, 2, 30, 4, 5]

Tip: Use this method to inset an element at a specific index.

function insertElementAtIndex(array, index, elem) {
   array.splice(index, 0, elem);
}
19. Slice

The slice() method returns a shallow copy of a portion of an Array.

var array = [1,2,3,4,5];

array.slice(1); // [2, 3, 4, 5] --> slice starts from index 1 to end

array.slice(1,3); // [2,3]--> slice from index 1 to (3-1)

Tip: Get last element of the array:

// get last n elements

array.slice(-n);

n = 1

array.slice(-1); 5

if n = 3

array.slice(-3); //  [3, 4, 5];
20. forEach

Executes a callback function once for each Array element. We cannot use break and continue in forEach, map functions.

var numbers = [1,2,3,4,5]

numbers.forEach((e) => {

  console.log(e)
	
});

Thank you for reading !

Sorting Method of Arrays in JavaScript

Sorting Method of Arrays in JavaScript

Understanding the Sort Method of Arrays

Understanding the Sort Method of Arrays. How to use JavaScript’s sort?

  • The JavaScript array sort() is used to sort array elements.
  • By default, the array will sort in ascending order, but we can change it.
  • This method willchange the original array.
  • We can also provide our comparing function to implement custom sorting.
var array = [1,2,3,1,2,3];

array.sort(); [1,1,2,2,3,3]

Let’s try another example:

var array = [1,2,11];

array.sort(); // [1,11,2]

For the above code, the expected result is [1,2,11], but we get [1,11,2]. The reason is the sort method converts the elements into strings then compares their sequences of UTF-16 code units values.

So the 11 is converted to β€œ11”. When we compare two strings like β€œ11” and β€œ2”, the char code is compared means char code of 1 is 49 , whereas char code of 2 is 50. Because of 49 < 50, we get [1,11,2].

If the array contains any undefined, then all undefined elements are sorted to the end of the array. We can use the default sort method to sort strings.

var names = ["John", "Abu", "Babu", "Balu", "Antony"]

names.sort();

console.log(names); // ["Abu", "Antony", "Babu", "Balu", "John"]

For other types, we need to pass our compareFunction as an argument to sort Function. The compare function takes two arguments. The two arguments are taken as from array on index [0,1] , [1,2] … [arrayLength-2, arrayLength-1] for comparing the pair of elements.

The sorting of elements is based on the return value of compareFunction for each pair of comparison. If the function returns…

  • >0 then the position of a and b is swapped.
  • <=0 then there is no change in position

Let’s write a compare function to sort numbers.

function compare(a, b) {

  if (a < b ) {
    return -1;
  }
	
  if (a > b ) {
    return 1;
  }
	
  // otherwise a == b
  return 0;
	
}

// Now if we execute
 
var array = [2,1,11];
array.sort(compare);

log(array); [1,2,11];

The above compare function can be simplified as:

function compareNumbers(a, b) {

  return a - b;
	
}

Because, when we do a-b, if a > b then it returns number > 0. If a<b, then it returns < 0. When a=b , then it returns 0.

To sort numbers in Descending Order, just change the a-b to b-a .

function Descending(a, b) {

    return b- a; 
		
}

Sorting Array of Objects

var users = [ {name: "John", age:20}, {name:"Antony" , age : 33}];

function sortByAge(obj1, obj2) {

    return obj1.age - obj2.age;
		
}

function sortByName(obj1, obj2) {
   return obj1.name.localeCompare(obj2.name);
} 

users.sort(sortByAge);

// output 
0: {name: "John", age: 20}
1: {name: "Antony", age: 33}

users.sort(sortByName);

//output

0: {name: "Antony", age: 33}
1: {name: "John", age: 20}

The **localeCompare()** method used in sortByName compareFunction returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

If the CompareFunction returns undefined, null, NaN, Infinity, then the array will not sort two members

var array = [3,2,1, 110, 102 , 30];

function customCompare(a, b){
   if(a > 10 || b > 10) {
      return Infinity;
   }
   else {
      return a-b;
   }
}

array.sort(customCompare);

In the above example, we have defined if the a and b is less than 10 , it will sort by ascending order. Otherwise, the function will return Infinity, though Infinity > 0. But, it will not be swapped. This is the same for undefined, null, NaN.

Thank you for reading !

14 Feature and Syntax in Javascript You Might Not Have Heard Of

14 Feature and Syntax in Javascript You Might Not Have Heard Of

I’ve been working with JavaScript for years now and to date, every now and then, I still stumble upon some hidden syntax or tricks that I never knew existed. Read more "14 Feature and Syntax in Javascript You Might Not Have Heard Of"

I’ve been working with JavaScript for years now and to date, every now and then, I still stumble upon some hidden syntax or tricks that I never knew existed.

I’ve tried to list down some of the lesser known features of JavaScript. While some of these features are invalid in the strict mode, they are still perfectly valid JavaScript code. However please note, I do not suggest that you start using all of these features. While they are definitely cool, there is a good chance you might start getting angry looks from your teammates, if you start using them.

1. Comma operator

JavaScript has a comma operator. It allows us to write multiple expressions separated by comma in a single line and return the result of last expression

// syntax
let result = expression1, expression2,... expressionN

Here, all the expressions will get evaluated and the result variable will be assigned the value returned by expressionN.

You might have already used Comma operator in a for loop

for (var a = 0, b = 10; a <= 10; a++, b--)

Sometimes it helps when writing multiple statements in a single line

function getNextValue() {
    return counter++, console.log(counter), counter
}

or writing short lamda functions

const getSquare = x => (console.log (x), x * x)
2. Getters & Setters

For the most parts, JavaScript Objects are simple. Let’s say if we have a user object and we try to access age property on it using user.age we get the value of age property if its defined or we get undefined if it’s not. Simple.

But, it doesn’t have to be this simple. JavaScript Objects have the concept of Getters and Setters. Instead of directly returning the value on object we can write our custom Getter function to return whatever we want. Same thing about setting a value.

This allows us to have powerful concepts like **virtual fields, field validations, side-effects**while getting or setting a field

ES5 Getters & Setters

Getters & Setters are not new addition by ES5; they have always been there. ES5 simply adds a convenient syntax to an existing feature. To learn more about Getters & Setters refer this nice article

3. !! Bang Bang Operator

Okay, technically its not a separate JavaScript operator. It’s just the JavaScript negation operator used twice.

But Bang Bang sounds so cool! Bang Bang or Double Bang is a neat trick to convert any expression to a Boolean value.

If the expression is a truthy value, it return true; otherwise it returns false.

Bang Bang operator

4. Tagged Template Literals

Unless you’ve been living under a rock, you would have heard about the Template literals. Template literals are one of the many cool additions by ES6. However, do you know about Tagged Template literals?

Template literals

Tagged Template literals allow you to have more control over parsing the template literals to a string, by adding a custom tag to the template literals. Tag is simply a parser function which gets array of all the strings and values interpreted by the string template. The tag function is expected to return the final string.

In following example, our custom tagβ€Šβ€”β€Šhighlight, interprets the values for template literal and also wraps the interpreted values in the result string with a element, for highlighting.

highlight tagged template literal

5. ~ Tilde Operator

Let’s face it β€” Nobody cares about the Bitwise operators.
When are we ever gonna use it!

Well, there is an everyday use case for the Tilde or Bitwise NOT operator.

Turns out when used with a number, the Tilde operator effective does
~N => -(N+1) . This expression evaluates to β€œ0” only when N == -1

We can leverage this by putting ~ in front of theindexOf(...) function to do a boolean check if an item exists in a String or an Array.

indexOf with Tilde operator

Note: ES6 & ES7 added a new .includes() method in String & Array, respectively. Definitely, it’s a more cleaner way than tilde operator to check if an item exists in an Array or a String.

6. Void Operator

JavaScript has a unary void operator. You might have seen it used as void(0) or void 0 . It has a single purpose in life β€” Evaluate the expression to its right and return undefined. Using β€˜0’ is just a convention. You don’t necessarily have to use β€˜0’, it can be any valid expression like void and it still returns undefined.

void operator

7. Constructor Brackets are optional

Yes, the parentheses we add after class name while invoking a constructor β€” completely optional! (Provided that you don’t need to pass any arguments to the Constructor)

Both the code styles below are considered to be valid JS syntax, and will give you exact same results!

Constructor brackets are optional

8. IIFE Brackets can be skipped

The syntax for IIFE (Immediately Invoked Functional Expression) was always a bit odd for me.
What’s up will all the brackets?

Well turns out those extra brackets are needed just to tell the JavaScript parser, that the upcoming code is a Functional Expression and not a Function. Knowing this, one can imagine, there are many ways to skip those extra brackets & still make a valid IIFE.

IIFE (without return)

The void operator tells parser that the code is functional expression. Hence, we can skip brackets around function definition. And guess what? We can use any unary operators (void, +, !, -, etc.) and this still works!

This is so cool!

However, if you are a keen observer, you may wonder,

Won’t the unary operator affect any result returned from the IIFE ?

Well, it will affect the result. But the good news is, if you care about the result and say you are storing it in some variable, then you don’t need the extra brackets in the first place.

That’s true!

IIFE with return

We add those brackets just for better human readability.

For a deeper dive on IIFE checkout this cool article by Chandra Gundamaraju

9. With Statement

Did you know, JavaScript has a with statementblock? with is actually a keyword in JS. The syntax to write a with block is as follows

with (object)
   statement 
// for multiple statements add a block
with (object) {
   statement
   statement
   ...
}

with adds all the properties of the β€œobject” passed, in the scope chain used for evaluating the statements.

with block example

10. The Function constructor

The function statement is not the only way to define a new function; you can define your function dynamically using Function() constructor along with the new operator.

Dynamic function with Function constructor

The last constructor param is the stringified code of the function and other parameters before that are the function arguments.

11. Function Properties

We all know Functions are first class objects in JavaScript. Hence, no one is stopping us from adding custom properties to a Function. It is perfectly valid JS thing to do. Yet, it is rarely used.

So when would we want to do this?

Well, there are a few good use cases for this. For example,

Configurable Functions

Let’s say we have a function called greet. We want our function to print a different greeting message based on different locales. This locale should also be configurable. We can maintain a global locale variable somewhere or we can implement the function using functional properties as shown below

greet function with locale property

Function with Static Variables

Another similar example. Let’s say, you want to implement a Number Generator that generates a sequence of ordered numbers. Normally, you’ll use Class or IIFE with a static counter variable to keep track of last value. This way we restrict access to the counter and also avoid polluting the global space with extra variables.

But what if we want the flexibility to read or even modify the counter & yet not pollute the global space?

Well we could still create a Class, with a counter variable and some extra methods to read it; or we can be lazy and just use properties on a function.

generateNumber function with counter property

Phew!! This is a long list & we are just about halfway there. If you wanna take a break, now will be a good time. If not, you are a brave warrior & I salute you.

Let’s continue!

12. Arguments Properties

I’m sure most of you are aware of arguments object inside a function. It’s an array like object available inside all the functions. It has the list of arguments passed to the function while it was invoked. But it also has some other interesting properties on it,

  • arguments.callee: Refers to the function currently invoked
  • arguments.callee.caller: Refers to the function that has invoked the current function

callee & caller

13. + Plus Operator

Ever wanted to quickly convert a string to a number?

Just prefix the string with + operator.
Plus operator also works for negative, octal, hexadecimal, exponential values. What’s more, it even converts a Date or Moment.js object to the timestamp!

Plus operator

14. Labelled statements

JavaScript has the concept of label statements. It allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later while using break or continue .

Labelled statements are particularly handy in nested loops. But we can also use them to simply organize code into blocks or create a breakable block

labelled statements

Note: Unlike some other languages, JavaScript doesn’t have goto construct. Hence, we can only use labels with break and continue.

You may also like: 10 More Useful Angular Features You Might Not Have Heard Of

If you know any more of such JavaScript quirks or have found interesting use-cases to leverage these features, please share your experiences below. I would love to hear about it!

All the source code used is available here.

Happy Coding!!!!!!!!!

How to Dynamically Sort an Array of Objects in JavaScript

How to Dynamically Sort an Array of Objects in JavaScript

In this JavaScript tutorial show you how to dynamically sort an array of objects in JavaScript, using Array.prototype.sort() and a custom compare function.

If you have an array of objects that you need to sort into a certain order, you might be tempted to reach for a JavaScript library. But before you do, remember that you can do some pretty neat sorting with the native Array.sort function.

In this article, we’ll show you how to sort an array of objects in JavaScript with no fuss or bother.

Basic Array Sorting

By default, the JavaScript Array.sort function converts each element in the array that needs to be sorted into a string, and compares them in Unicode code point order.

const foo = [9, 1, 4, 'zebroid', 'afterdeck'];
foo.sort(); // returns [ 1, 4, 9, 'afterdeck', 'zebroid' ]

const bar = [5, 18, 32, new Set, { user: 'Eleanor Roosevelt' }];
bar.sort(); // returns [ 18, 32, 5, { user: 'Eleanor Roosevelt' }, Set {} ]

You may be wondering why 32 comes before 5. Not logical, huh? Well, actually it is. This happens because each element in the array is first converted to a string, and "32" comes before "5" in Unicode order.

It’s also worth noting that unlike many other JavaScript array functions, Array.sort actually changes, or mutates the array it sorts.

const baz = ['My cat ate my homework', 37, 9, 5, 17];
baz.sort(); // baz array is modified
console.log(baz); // shows [ 17, 37, 5, 9, 'My cat ate my homework' ]

To avoid this, you can create a new instance of the array to be sorted and modify that instead. This is possible using an array method that returns a copy of the array. For example, Array.slice:

const sortedBaz = baz.slice().sort(); // a new instance of the baz array is created and sorted

Or if you prefer a newer syntax, you can use the spread operator for the same effect:

const sortedBaz = [...baz].sort(); // a new instance of the baz array is created and sorted

The output is the same in both cases:

console.log(baz); // ['My cat ate my homework', 37, 9, 5, 17];
console.log(sortedBaz); // [ 17, 37, 5, 9, 'My cat ate my homework' ]

Try it out

Using Array.sort alone wouldn’t be very useful for sorting an array of objects. Thankfully, the function takes an optional compareFunction parameter, which causes the array elements to be sorted according to the return value of the compare function.

Using Compare Functions to Sort

Let’s say that foo and bar are the two elements being compared by the compare function, and the return value of the compare function is set up as follows:

  1. less than 0 β€” foo comes before bar
  2. greater than 0 β€Šβ€” bar comes before foo
  3. equal to 0β€Š β€” foo and bar are left unchanged with respect to each other.

Let’s look at a simple example with an array of numbers:

const nums = [79, 48, 12, 4];

function compare(a, b) {
  if (a > b) return 1;
  if (b > a) return -1;

  return 0;
}

nums.sort(compare);
// => 4, 12, 48, 79

We can refactor this a little, as subtracting a from b will also give us the return value:

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

This is now a good candidate for an arrow function:

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

How to Sort an Array of Objects in JavaScript

Now let’s look at sorting an array of objects. For this demo we’ll use an array of singers:

const singers = [
  { name: 'Steven Tyler', band: 'Aerosmith', born: 1948 },
  { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 },
  { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 },
  { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 },
];

We can use the following compare function to sort this array of singers according to their band:

function compare(a, b) {
  // Use toUpperCase() to ignore character casing
  const bandA = a.band.toUpperCase();
  const bandB = b.band.toUpperCase();

  let comparison = 0;
  if (bandA > bandB) {
    comparison = 1;
  } else if (bandA < bandB) {
    comparison = -1;
  }
  return comparison;
}

singers.sort(compare);

/* returns [
  { name: 'Steven Tyler', band: 'Aerosmith',  born: 1948 },
  { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 },
  { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 },
  { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 }
] */

To reverse the sorting order, you can invert the return value of the compare function:

function compare(a, b) {
  ...

  //invert return value by multiplying by -1
  return comparison * -1;
}

Try it out

Creating a Dynamic Sorting Function

Let’s finish up by making this more dynamic. Let’s create a sorting function, which you can use to sort an array of objects, whose values are either strings or numbers. This function has two parameters β€” the key we want to sort by and the order of the results (i.e. ascending or descending):

const singers = [
  { name: 'Steven Tyler', band: 'Aerosmith', born: 1948 },
  { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 },
  { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 },
  { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 },
];

function compareValues(key, order = 'asc') {
  return function innerSort(a, b) {
    if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
      // property doesn't exist on either object
      return 0;
    }

    const varA = (typeof a[key] === 'string')
      ? a[key].toUpperCase() : a[key];
    const varB = (typeof b[key] === 'string')
      ? b[key].toUpperCase() : b[key];

    let comparison = 0;
    if (varA > varB) {
      comparison = 1;
    } else if (varA < varB) {
      comparison = -1;
    }
    return (
      (order === 'desc') ? (comparison * -1) : comparison
    );
  };
}

And this is how you’d use it:

// array is sorted by band, in ascending order by default
singers.sort(compareValues('band'));

// array is sorted by band in descending order
singers.sort(compareValues('band', 'desc'));

// array is sorted by name in ascending order
singers.sort(compareValues('name'));

// array is sorted by date if birth in descending order
singers.sort(compareValues('born', 'desc'));

Try it out

In the code above, the hasOwnProperty method is used to check if the specified property is defined on each object and has not been inherited via the prototype chain. If it’s not defined on both objects, the function returns 0, which causes the sort order to remain as is (i.e. the objects remain unchanged with respect to each other).

The typeof operator is also used to check the data type of the property’s value. This allows the function to determine the proper way to sort the array. For example, if the value of the specified property is a string, a toUpperCase method is used to convert all its characters to uppercase, so character casing is ignored when sorting.

You can adjust the above function to accommodate other data types, and any other needs your script may have.

String.prototype.localeCompare()

In our example above, we want to be able to sort an array of objects, whose values are either strings or numbers. If, however, you know that you’ll only be dealing with objects whose values are strings, you can tidy up the code a little using JavaScript’s localeCompare method.

This method returns a number indicating whether a string comes before, after, or is the same as a given string in the sort order. It enables a case-insensitive sort of an array:

['bjork', 'Bjork', 'BjΓΆrk'].sort();
// [ 'Bjork', 'BjΓΆrk', 'bjork' ]

['bjork', 'Bjork', 'BjΓΆrk'].sort((a, b) => a.localeCompare(b));
//  [ 'bjork', 'Bjork', 'BjΓΆrk' ]

In terms of our compareValues function, that means we could write:

function compareValues(key, order = 'asc') {
  return function innerSort(a, b) {
    if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return 0;
    const comparison = a[key].localeCompare(b[key]);

    return (
      (order === 'desc') ? (comparison * -1) : comparison
    );
  };
}

You can read more about localeCompare over on MDN.

Conclusion

So there you have it β€” a short introduction to sorting an array of objects using vanilla JavaScript. Although many libraries offer this kind of dynamic sorting ability, as demonstrated, it’s not all that hard to implement this functionality yourself. Plus it’s good to understand what is going on under the hood.