遍历数组以查找等于指定总和的值

时间:2019-08-05 08:48:25

标签: javascript

我正在尝试编写一个将产生以下输出的函数:

$('#TmOnSite').on('changeTime', function() {
    var x = $("#TmOnSite").val();                    
});

我尝试过,

// Required sum

console.log([3, 4, 2, 1, 2, 3, 6, 0].elementsTheSumTo(6)) // [ [3, 3], [4, 2], [6, 0] ]

console.log([7, 0, 5, 8, 0, 0, 7, 7].elementsThatSumTo(7)) // [ [7, 0], [0, 7], [0, 7], [0, 7] ]

但是,这产生了意外的行为。我也在考虑使用Array.prototype.elementsThatSumTo = n => { let result = []; for (let i = 0; i < this.length; i++) { for (let j = 0; j < this.length; j++) { if (j !== i && (this[i] + this[j] === n) { result.push([ this[i], this[j] ]); } } } return result; } ,但这似乎也不起作用。不确定如何弄清楚这一点。

4 个答案:

答案 0 :(得分:2)

找到匹配项后,您需要从数组中删除元素,这可以通过splice完成。您还需要使用完整的function访问数组实例this

Array.prototype.elementsThatSumTo = function(n) {
    const arr = this.slice(); // avoid mutating the input array
    const result = [];
    while (arr.length) {
        const num1 = arr.shift();
        const num2Index = arr.findIndex(num => num1 + num === n);
        if (num2Index === -1) {
            continue;
        }
        result.push([num1, arr[num2Index]]);
        arr.splice(num2Index, 1);
    }
    return result;
}

console.log([3, 4, 2, 1, 2, 3, 6, 0].elementsThatSumTo(6)) // [ [3, 2], [4, 2], [6, 0] ]

console.log([7, 0, 5, 8, 0, 0, 7, 7].elementsThatSumTo(7)) // [ [7, 0], [0, 7], [0, 7], [0, 7] ]

请记住,对内置原型进行变异是非常的错误做法。如果可能的话,请考虑使用独立功能:

const elementsThatSumTo = (arrInit, n) => {
    const arr = arrInit.slice(); // avoid mutating the input array
    const result = [];
    while (arr.length) {
        const num1 = arr.shift();
        const num2Index = arr.findIndex(num => num1 + num === n);
        if (num2Index === -1) {
            continue;
        }
        result.push([num1, arr[num2Index]]);
        arr.splice(num2Index, 1);
    }
    return result;
}

console.log(elementsThatSumTo([3, 4, 2, 1, 2, 3, 6, 0], 6)) // [ [3, 2], [4, 2], [6, 0] ]

console.log(elementsThatSumTo([7, 0, 5, 8, 0, 0, 7, 7], 7)) // [ [7, 0], [0, 7], [0, 7], [0, 7] ]

答案 1 :(得分:1)

这是因为对于每个数字,您还将看到已经涵盖的组合。只需将代码中的(j = 0)更改为(j =(i + 1)),它就可以正常工作,然后您也可以忽略检查(j == i)。

Array.prototype.elementsThatSumTo = function(n) {
  let result = [];
  for (let i = 0; i < this.length; i++) {
      for (let j = (i+1); j < this.length; j++) {
          if (this[i] + this[j] === n) {
              result.push([ this[i], this[j] ]);
          }
      }
  }

  return result;
}

console.log([3, 4, 2, 1, 2, 3, 6, 0].elementsThatSumTo(6)) // [ [3, 3], [4, 2], [6, 0] ]

console.log([7, 0, 5, 8, 0, 0, 7, 7].elementsThatSumTo(7)) // [ [7, 0], [0, 7], [0, 7], [0, 7] ]

答案 2 :(得分:1)

您可以使用Map并存储访问的元素并找出出现的位置。

Array.prototype.elementsThatSumTo = function (sum) {
    var map = new Map,
        i, l, v
        result = [];
    for (i = 0, l = this.length; i < l; i++) {
        v = this[i];
        if (map.get(v)) {
            map.set(v, map.get(v) - 1);
            result.push([sum - v, v]);
            continue
        }        
        map.set(sum - v, (map.get(sum - v) || 0) + 1);
    }
    return result;
}

console.log([3, 4, 2, 1, 2, 3, 6, 0].elementsThatSumTo(6)) // [ [3, 2], [4, 2], [6, 0] ]
console.log([7, 0, 5, 8, 0, 0, 7, 7].elementsThatSumTo(7)) // [ [7, 0], [0, 7], [0, 7], [0, 7] ]

答案 3 :(得分:1)

Array.prototype.elementsThatSumTo = function(n) {

  var result = [],
    len = this.length;
  for (var i = 0; i < len - 1; i++)
    for (var j = i + 1; j < len; j++)
      if (this[i] + this[j] == n)
        result.push([this[i], this[j]]);

  return result;
}


console.log([3, 4, 2, 1, 2, 3, 6, 0].elementsThatSumTo(6))