在 JavaScript 中查詢無序的陣列元素
假設我們有一個已排序的數字陣列,但陣列中的一些元素超出其排序順序了。
我們要求編寫一個 JavaScript 函式,該函式接受這樣的一個數組,並返回一個子陣列,其中包含所有無序元素。
示例
該程式碼如下 −
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));
輸出
在控制檯中的輸出 −
[ '7', '1' ]
廣告