鍍金池/ 問答/HTML/ es6如何優(yōu)雅的判斷兩個數(shù)組包含的值完全相同,順序無所謂

es6如何優(yōu)雅的判斷兩個數(shù)組包含的值完全相同,順序無所謂

這是我現(xiàn)在的做法,請問還有更好一些的方式么

let flag = true
    const listA = [1, 2, 3]
    const listB = [2, 3, 4]
    if (listA.length !== listB.length) {
      flag = false
    } else {
      listA.forEach(item => {
        if (listB.indexOf(item) === -1) {
          flag = false
        }
      })
    }
回答
編輯回答
蝶戀花

一句就能搞定:

const listA = [1, 2, 3]
const listB = [2, 3, 1]

const result = listA.length === listB.length && listA.every(a => listB.some(b => a === b)) && listB.every(_b => listA.some(_a => _a === _b));

console.log(result);
//true
2017年12月3日 04:53
編輯回答
雅痞

你可以首先排序,然后遍歷一遍,這樣時間復(fù)雜度主要就是排序的時間復(fù)雜度了;

但是我覺得這段代碼還有可以優(yōu)化的地方:

function isSame (a, b) {
  if (a.length !== b.length) return false

  let c = b.slice()
  // 在可以提前退出的情況下不要使用forEach
  for (let i = 0, len = a.length; i < len; i++) {
    let j = c.indexOf(a[i])
    if ( j === -1) return false
    c.splice(j, 1) // 刪除已經(jīng)匹配的元素,可以縮短下次匹配的時間
  }
  return true
}
isSame([1, 2, 2], [1, 1, 2]) // false
isSame([1, 2, 2], [2, 1, 2]) // true
2018年2月5日 02:51
編輯回答
背叛者

你這個寫法我也沒看懂, 測試了一下
[1,2,3]和[1,2,3]返回false,
[1,2,3]和[2,3,4]也返回false

2017年6月23日 08:22
編輯回答
純妹

如果數(shù)組元素是純字符的話,可以試試以下:

function isEqual(arr1, arr2) {
  return JSON.stringify(arr1.sort()) === JSON.stringify((arr2.sort()))
}

// true
isEqual([1, 5, 'string', 2], [1, 2, 5, 'string'])
2017年12月25日 23:43
編輯回答
絯孑氣

如果是純字符,可以先排序然后轉(zhuǎn)化成字符串直接比較 使用sort 和 join 這兩個函數(shù)就搞得定吧

2018年3月14日 17:49
編輯回答
孤星

如果有重復(fù) 你這判斷 是錯誤的

const listA = [1, 2, 2]
const listB = [1, 1, 2]

如果只是基本 類型 建議 sort 之后 意義對比
如果是 復(fù)雜類型 還要遞歸 對比

2018年3月2日 19:05
編輯回答
我不懂

方法1:先兩個數(shù)組用同樣的方式排序,再字符串化比較
方法2:把兩個數(shù)組分別放到Set里面去,再把其中一個Set add到另外一個Set,如果長度沒變兩數(shù)組元素相同

2017年4月7日 13:46
編輯回答
離人歸
const listA = [1, 2, 3]
const listB = [3, 2, 1]
Array.prototype.equals = function(arr)
{
    return this.sort().join() === arr.sort().join()
}
console.log(listA.equals(listB))
2017年12月13日 13:10