Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find array elements that are out of order in JavaScript
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' ]
How It Works
The function uses the filter() method with a custom this context to track the expected next value. It converts string elements to numbers using the unary + operator and identifies elements that break the sequential order.
Alternative Approach
Here's a more readable version that finds out-of-order elements:
const arr2 = [1, 2, 5, 3, 4, 8, 6];
const findOutOfOrder2 = (arr) => {
const outOfOrder = [];
const sorted = [...arr].sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== sorted[i]) {
outOfOrder.push(arr[i]);
}
}
return outOfOrder;
};
console.log(findOutOfOrder2(arr2));
[ 5, 3, 4, 8, 6 ]
Conclusion
Both approaches effectively identify out-of-order elements. The first uses a clever filter technique with context tracking, while the second compares against a sorted version for clearer logic.
