最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript: Compare two arrays and return index of matches - Stack Overflow

programmeradmin3浏览0评论

I have the following code.

function findMatch(array_1_small, array2_large) {
var ary = new Array();
for(i = 0;i < array2_large.length; i++)
{
  for(z = 0; z < array_1_small.length; z++)
  {
    if(array2_large[i] == array_1_small[z])
    {
     var idx = array2_large.indexOf(array2_large[i]);
      ary.push(idx);
    }
  }

}
return ary;
}

That takes the following arrays.

var all_SMS_TO = ["0861932936", "0871355066", "0874132026", "0872908445", "0874132026"];
var all_FORM_NUMBERS = ["", "", "", "", "", "", "0871355066",""];

The sole purpose is to find a match and return the index of the match on the 'all_form_numbers array.

On calling the code

var a = findMatch(all_SMS_TO, all_FORM_NUMBERS);
console.log("Match Found " + a);

I get the following output.

Match Found: 6

Which is correct, however when I alter the all_form_Numbers array to

var all_FORM_NUMBERS = ["", "0871355066", "", "", "", "", "0871355066",""];

I get The following output.

Match Found: 1,1

Could somebody help me with this so it should output;

Match Found 1, 6.

Thanks.

I have the following code.

function findMatch(array_1_small, array2_large) {
var ary = new Array();
for(i = 0;i < array2_large.length; i++)
{
  for(z = 0; z < array_1_small.length; z++)
  {
    if(array2_large[i] == array_1_small[z])
    {
     var idx = array2_large.indexOf(array2_large[i]);
      ary.push(idx);
    }
  }

}
return ary;
}

That takes the following arrays.

var all_SMS_TO = ["0861932936", "0871355066", "0874132026", "0872908445", "0874132026"];
var all_FORM_NUMBERS = ["", "", "", "", "", "", "0871355066",""];

The sole purpose is to find a match and return the index of the match on the 'all_form_numbers array.

On calling the code

var a = findMatch(all_SMS_TO, all_FORM_NUMBERS);
console.log("Match Found " + a);

I get the following output.

Match Found: 6

Which is correct, however when I alter the all_form_Numbers array to

var all_FORM_NUMBERS = ["", "0871355066", "", "", "", "", "0871355066",""];

I get The following output.

Match Found: 1,1

Could somebody help me with this so it should output;

Match Found 1, 6.

Thanks.

Share Improve this question asked Feb 6, 2017 at 14:48 Andrew DalyAndrew Daly 5373 silver badges13 bronze badges 5
  • 3 Isn't i is the index? ary.push(i). IndexOf will do another O(n) search, and return the first index it finds, which you don't need in your case since you know the index already. – greedy52 Commented Feb 6, 2017 at 14:51
  • Possible duplicate of Simplest code for array intersection in javascript – Scott Marcus Commented Feb 6, 2017 at 14:52
  • Variables i and z should be declared with let or var. – Pointy Commented Feb 6, 2017 at 14:52
  • 2 var a = all_FORM_NUMBERS.map((n, i) => all_SMS_TO.includes(n) ? i : -1).filter(n => n != -1) jsfiddle/d5waz2bL – user1106925 Commented Feb 6, 2017 at 14:58
  • Very clever ideas here especially with the map! Thanks. – Andrew Daly Commented Feb 6, 2017 at 15:51
Add a ment  | 

4 Answers 4

Reset to default 3

try this:

function findMatch(array_1_small, array2_large) {
var ary = new Array();
for(i = 0;i < array2_large.length; i++)
{
  for(z = 0; z < array_1_small.length; z++)
  {
    if(array2_large[i] == array_1_small[z])
    {
      ary.push(i);
    }
  }

}
return ary;
}

When you do

var idx = array2_large.indexOf(array2_large[i]);

you are searching for the index of the value 0871355066 in the array array2_large twice and as per the definition of indexOf it will returns the position of the first occurrence of a specified value.

This is why you are getting index value 1 twice since its the index of first occurrence.

For solution Just push the variable i value into the array ary. Which is already the index value of array2_large in the loop.

function findMatch(array_1_small, array2_large) {
var ary = new Array();
for(i = 0;i < array2_large.length; i++)
{
  for(z = 0; z < array_1_small.length; z++)
  {
    if(array2_large[i] == array_1_small[z])
    {
      ary.push(i);
    }
  }

}
return ary;
}


var all_SMS_TO = ["0861932936", "0871355066", "0874132026", "0872908445", "0874132026"];
//var all_FORM_NUMBERS = ["", "", "", "", "", "", "0871355066",""];

var all_FORM_NUMBERS = ["", "0871355066", "", "", "", "", "0871355066",""];


var a = findMatch(all_SMS_TO, all_FORM_NUMBERS);
console.log("Match Found " + a);

You just need to push the index i here is the fixed code (you can also declare an array as var res = [];

function findMatch(arraySmall, arrayLarge) {
  var res = []
  for (var i = 0; i < arrayLarge.length; i++) {
    for (var j = 0; j < arraySmall.length; j++) {
      if (arrayLarge[i] === arraySmall[j]) {
        res.push(i);
      }
    }
  }
  return res;
}

It is possible to solve this on O(n+m) runtime plexity by creating a lookup table of positions first. Then you map each element from the first array to all positions and collect these indices in a Set to only leave unique values.

Try this:

var all_SMS_TO = ["0861932936", "0871355066", "0874132026", "0872908445", "0874132026"];
var all_FORM_NUMBERS = ["", "0871355066", "", "", "", "", "0871355066",""];

function findMatch(array_1_small, array2_large) {
    var positions = Array.from(array2_large.entries()).reduce((acc, t) => {
        var index = t[0]
        var element = t[1]
        if (!acc.hasOwnProperty(element)) {
            acc[element] = []
        }
        acc[element].push(index)
        return acc
    }, {})
    var result = new Set()
    array_1_small.forEach(x => {
        if (positions[x] === undefined) {
            return
        }
        positions[x].forEach(index => result.add(index))
    })
    return Array.from(result)
}

console.log("Match found: " + findMatch(all_SMS_TO, all_FORM_NUMBERS))

发布评论

评论列表(0)

  1. 暂无评论