Add to an array from matched key

2019-08-19 00:37发布

问题:

I'm not entirely sure how to title the question, but I'm trying to add to one Array from a second based on a matched string at index 0. This is in a Google Apps Script web app, which is why it's all JavaScript-based rather than PHP.

// Sent from client
Array1: ["A"]

// Stored on server
Array2: [["A", "June","15"], ["B","October","30"]]

I'd like to return the entire matching array based on the client-submitted form object.

I've tried:

Array1 = Array1.filter(function(val) {
  return Array2.indexOf(val) !== -1;    // I thought this would return indices that matched
});

but I get an empty array returned instead of ["A","June","15"]. Any ideas?

回答1:

You used wrong filter function.You have to filter Array2 based on Array1 values.

var Array1= ["A","B"]
var Array2=[["A", "June","15"], ["B","October","30"],["C","September","16"]]
var result = Array2.filter(function(val) {
  return Array1.indexOf(val[0])!=-1;
});
console.log(result);