JavaScript 中的兩個陣列的相等性
我們需要編寫一個 JavaScript 函式,該函式接收兩個數字陣列(比如 first 和 second),並檢查它們是否相等。
我們案例中的相等性將由以下兩個條件之一決定:
如果陣列包含相同的元素(不考慮它們的順序),則它們相等。
如果第一個陣列和第二個陣列所有元素的總和相等。
例如:
[3, 5, 6, 7, 7] and [7, 5, 3, 7, 6] are equal arrays [1, 2, 3, 1, 2] and [7, 2] are also equal arrays but [3, 4, 2, 5] and [2, 3, 1, 4] are not equal
讓我們編寫此函式的程式碼:
示例
const first = [3, 5, 6, 7, 7]; const second = [7, 5, 3, 7, 6]; const isEqual = (first, second) => { const sumFirst = first.reduce((acc, val) => acc+val); const sumSecond = second.reduce((acc, val) => acc+val); if(sumFirst === sumSecond){ return true; }; // do this if you dont want to mutate the original arrays otherwise use first and second const firstCopy = first.slice(); const secondCopy = second.slice(); for(let i = 0; i < firstCopy.length; i++){ const ind = secondCopy.indexOf(firstCopy[i]); if(ind === -1){ return false; }; secondCopy.splice(ind, 1); }; return true; }; console.log(isEqual(first, second));
輸出
控制檯中的輸出將為:
true
廣告