Check if two arrays have the same values

后端 未结 9 1377
既然无缘
既然无缘 2020-12-15 02:45
[2,5,3]    

[5,2,3]

They are equal because they have the same values, but not in the same order. Can I find out that without using a foreach loop

9条回答
  •  -上瘾入骨i
    2020-12-15 03:21

    I came across this problem and solve it thus: I needed to ensure that two objects had the same fields So

    const expectedFields = ['auth', 'message'];
    const receivedFields = Object.keys(data);
    const everyItemexists = expectedFields.map(i => receivedFields.indexOf(i) > -1);
    const condition = everyItemexists.reduce((accumulator, item) => item && accumulator, true);
    

    Basically, go through one of the arrays, here (I'm assuming there are of the same size though). Then check if its exists in the other array. Then i reduce the result of that.

提交回复
热议问题