【问题标题】:javascript compare int arrays and calculate difference for eachjavascript比较int数组并计算每个数组的差异
【发布时间】:2019-03-02 17:37:53
【问题描述】:

我有 2 个不断修改的 json 文件。它们的格式是这样的:

[ 
  { 
    "rank": 1,
    "points": 10 
  },
  { 
    "rank": 15,
    "points": 1601 
  }
]

所以嵌套键的数量可以是任何值,在上面的示例中是 2。 我遍历文件并从每个嵌套键中获取我想要的值,并将它们放入一个数组中。 所以数组是这样的 const array1 = [ "1", "15" ] & const array2 = [ "18", "5" ] 等。 我现在有 2 个 json 文件 - 一个显示先前等级(修改前)的数组和一个显示当前等级的数组。 我想要做的是,循环遍历数组并减去它们之间的整数,这样我就可以创建一个像这样的字符串:“Rank:15 (-10)”(又名将指示它是增加还是减少以及如何很多。但由于数组可以无限大,我必须创建一个循环,将 array1[0] 与 array2[0] 等相减。

不知道怎么做,谁能帮帮我?

【问题讨论】:

  • 欢迎来到 SO!我对这个解释有点困惑;你能提供具体的输入和输出,预期的转换,和what you've tried so far吗?

标签: javascript arrays node.js loops foreach


【解决方案1】:

如果我的理解是正确的,你的情况是给定 2 个整数数组,你想显示差异吗?

/* given 2 arrays (of maybe non-equal length) */
const before = [10,20,30,40,50]
const after = [5,18,35,42,55,100]

/* derive the data needed */
const shorterArray = before.length <= after.length ? before : after
const pairs = shorterArray.map((ele, idx) => 
    ({
      points: ele,
      diff: ele - after[idx]
    })
  )
  
/* print output */
pairs.map(({points, diff}=x) =>             // use object destructuring to separate the elements
  console.log(`Rank: ${points} (${diff})`)) // print output

【讨论】:

    【解决方案2】:

    有点被你的问题弄糊涂了……但我会试一试。好像您只是将一个数组的索引位置与另一个数组进行比较,并提供一些输出。可以执行以下操作:

    const arr1 = [1, 15, 43];
    const arr2 = [18, 30, 12];
    
    const compareRanks = (oldArray, newArray) => {
      oldArray.forEach((oldRank, index) => {
        const newRank = newArray[index];
        console.log(`Rank: ${newRank}(${oldRank - newRank})`);
      });
    };
    
    compareRanks(arr1, arr2);
    

    值得注意的是,这个解决方案是脆弱的。它要求您的数组具有相同的大小,并且所有元素都是整数。如果你使用它,最好为它构建一些防护栏,否则如果给出的数据结构不正确,它将引发错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-25
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      相关资源
      最近更新 更多