是否有一个loadash函数可以比较两个数组并仅在arr1中存在来自arr2的所有值时才返回true?

时间:2019-04-08 09:10:57

标签: javascript arrays lodash

我必须比较两个数组,如果只有数组1包含数组2的所有值,则返回true。对此合适的loadash函数是什么?

CREATE TABLE bills (
    id              INTEGER NOT NULL,
    code        VARCHAR(25) NOT NULL, 
    dateOfGeneration   DATE NOT NULL,
    job_id     INTEGER NOT NULL,
  CONSTRAINT bills_pk PRIMARY KEY ( id,job_id )
)

将arr1与arr2比较应返回true 比较arr1和arr3应该返回false

6 个答案:

答案 0 :(得分:2)

出于完整性考虑,您可以选择Set并与Set#has进行比较。

let arr1 = [1, 2, 3, 4],
    arr2 = [1, 2],
    arr3 = [1, 5],
    base = new Set(arr1);

console.log(arr2.every(Set.prototype.has, base));
console.log(arr3.every(Set.prototype.has, base));

答案 1 :(得分:0)

您可以只使用every

let arr1 = [1, 2, 3, 4];
let arr2 = [1, 2];
let arr3 = [1, 5];

const allElements = (a1, a2) => a2.every(e => a1.includes(e));
console.log(allElements(arr1, arr2));
console.log(allElements(arr1, arr3));

答案 2 :(得分:0)

这里不需要重载,只需将本机JavaScript Array#every方法与Array#includes方法一起使用

function compareArray(arr1, arr2) {
  return arr2.every(v => arr1.includes(v))
}

let arr1 = [1, 2, 3, 4]
let arr2 = [1, 2]
let arr3 = [1, 5]

console.log(compareArray(arr1, arr2))
console.log(compareArray(arr1, arr3))

答案 3 :(得分:0)

let arr1 = [1, 2, 3, 4]
let arr2 = [1, 2] 

for(let x of arr2) {
    _.includes(arr1, x) || true;
}

答案 4 :(得分:0)

您可以使用_.difference

let arr1 = [1, 2, 3, 4]
let arr2 = [1, 2] 
let arr3 = [1, 5] 


console.log(_.difference(arr2,arr1).length === 0)
console.log(_.difference(arr3,arr1).length === 0)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

答案 5 :(得分:0)

您可以通过以下方式使用_.difference

let arr1 = [1, 2, 3, 4]
let arr2 = [1, 2] 

const b = _.difference(arr2, arr1).length === 0