简体   繁体   English

比较两个 arrays 的值,如果一个值被删除,则只返回差值,而不是添加

[英]Comparing the value of two arrays and only returning the difference if a value is removed, not added

I am working on a project with an array of values that could possibly change every 30 seconds.我正在开发一个项目,其中包含一组可能每 30 秒更改一次的值。 I need to compare the first array to the current array of values every time this runs and return the difference between the values ONLY if a value is removed.每次运行时,我都需要将第一个array与当前array的值进行比较,并且仅当删除了一个值时才返回值之间的差异。

For example if array1 = [12, 14, 16] and array2 = [12, 16, 18] , then I need to return 14 and do something with it.例如,如果array1 = [12, 14, 16]array2 = [12, 16, 18] ,那么我需要返回14并对其进行处理。 What would be the best way to accomplish this?实现这一目标的最佳方法是什么?

This is my current code, but it returns any difference between the two arrays:这是我当前的代码,但它返回两个 arrays 之间的任何差异:

function diffArr (array1, array2) {
  const temp = [];
  array1 = array1.toString().split(',').map(Number);
  array2 = array2.toString().split(',').map(Number);

  for (var i in array1) {
    if(!array2.includes(array1[i])) temp.push(array1[i]);
  }

  for(i in array2) {
    if(!array1.includes(array2[i])) temp.push(array2[i]);
  }

  return temp.sort((a,b) => a-b);
}

Try this:试试这个:


const array1 = [12, 14, 16, 20, 10]

const array2 = [12, 16, 18]

const diffArr = (array1, array2) => {
    const temp = array1.filter(ele => !array2.includes(ele))
    return temp.sort((a,b) => a-b);
}

console.log(diffArr(array1, array2)) // output = [ 10, 14, 20 ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 比较两个多维数组的最后一个值 - Comparing the last value of two multidimensional arrays useEffect 仅在将值添加到数组时运行,但在删除值时不运行 - useEffect only running when value is added to array but no when value is removed 比较两个数组时找到第一个匹配值javascript - find the first matching value when comparing two arrays javascript 在Javascript中比较两个数组 - 返回差异 - Comparing two arrays in Javascript - Returning differences 比较两个 arrays 并返回有效和错位的元素 - Comparing two arrays and returning valid and misplaced elements this.value仅返回前两个字符 - this.value only returning first two characters 从两个数组之间的差异中获取百分比值javascript - Get percentage value from difference between two arrays javascript 如何计算两个 arrays 在秒 position 时具有相同值的差异 - How to calculate difference of two arrays with same value at second position 只应在向其添加元素时增加高度的 Div,如果删除项目,则保持先前增加的高度值 - Div that should only grow in height while elements are added to it, and keep the previoused increased height value if items are removed 如何找到 mongodb 中返回计数值的两个查询之间的差异? - How to find the difference between two queries returning count value in mongodb?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM