Was it helpful?

Question

Find array elements that are out of order in JavaScript

JavascriptWeb DevelopmentObject Oriented ProgrammingFront End Technology

Suppose we have an array of sorted numbers but some elements of the array are out of their sorted order.

We are required to write a JavaScript function that takes in one such array and returns a subarray of all those elements that are out of order.

Example

The code for this will be −

const arr = ["2", "3", "7", "4", "5", "6", "1"];
const findOutOfOrder = arr => {
   let notInOrder = [];
   notInOrder = arr.filter((el, ind) => {
      return ind && this.next !== +el || (this.next = +el + 1, false);
   }, {
      next: null
   });
   return notInOrder;
};
console.log(findOutOfOrder(arr));

Output

The output in the console −

[ '7', '1' ]
raja
Published on 10-Oct-2020 11:17:41
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top