Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - Compare multiple indixes in array to multiple indixes in another array

I am wondering if there's a neat way to compare (!= or ==) several values in an array (so multiple indices) with several values (multiple indices) in another array. Let me explain a little more in-depth.

I have a continuous list input to a function, where I want to add the lists as "rows" to my data array, so something like this:

var data = new Array();

function compare() {
    // lets say all the input lists have 4 elements, example [100, 200, 300, 400]. 
    var input_list = arrayfromargs(arguments);
    
    // concat the input with my data variable.
    data = data.concat([input_list]);
} 

However, I do NOT want to add the input list as a row to the data array if there already exists a row in the data array with the same values at specific indices.

For instance, say I want to compare values at the last and second-to-last indices (so index 2 and 3 (values 300 and 400) in the example above). How can I best compare my input list values at the 2nd and 3rd index to every value at the 2nd and 3rd index in the data array rows?

I know that the most obvious way is to have nested if-else's inside a for-loop, however, this quickly becomes quite messy.

Any more refined or elegant ways to accomplish this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming you add the data array by array, you could maintain something like a hash table:

// lookup table to keep track of last two indices
var hashTable = {};

// array of arrays with no matching final pairs
var dataArray = [];

function addToArray(input) {
  // ignore short input arrays
  if (input.length < 2) return;
  // get the last two entries of the input array
  var a = input[input.length - 2];
  var b = input[input.length - 1];
  // return if we’ve seen these entries before
  if (hashTable[a] && hashTable[a][b]) return;
  // add the new entries to the hash table
  if (!hashTable[a]) {
    hashTable[a] = {};
  }
  hashTable[a][b] = true;
  // add the full input to the data array
  dataArray.push(input);
}

So with your sample data:

addToArray([1, 2, 3, 4]);
// hashTable = {
//   3: { 4: true }
// }

addToArray([5, 6, 7, 8]);
// hashTable = {
//   3: { 4: true },
//   7: { 8: true }
// }

addToArray([9, 10, 7, 8]);
// hashTable[7][8] === true, so this addition fails

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...