jQuery-如果数组匹配变量,则将其推送到新数组

时间:2017-09-26 22:02:09

标签: javascript arrays

我想从数组中创建新的数组

myArray = [
["9-15", "Text"],
["9-15", "Text"],
["8-15", "Text"],
]

如果选择的值等于myArray的任何元素。

<select>
<option value="8-17">8-17</option>
<option value="9-17">9-17</option>
</select >

它应该被推入我的新数组

$("select").change(function(){
  for (var i = 0; i < myArray; i++) {
    var newArr = [];
    if (myArray[i].includes( $(this).val() ) === true) {
        newArr( myArray[i] );
        console.log(newArr.length);
    }
  }
});

结果应该是

var newArr = [
    ["9-15", "Text"],
    ["9-15", "Text"]
]

2 个答案:

答案 0 :(得分:0)

你必须与myArray.length进行比较,另外你必须将项目添加到newArr(因为newArr不是函数)

$("select").change(function(){
  for (var i = 0; i < myArray.length; i++) {
    var newArr = [];
    if (myArray[i].includes( $(this).val() ) === true) {
        newArr.push( myArray[i] );
        console.log(newArr.length);
    }
  }
});

答案 1 :(得分:0)

let myArray = [
  ["9-15", "Text"],
  ["9-15", "Text"],
  ["8-15", "Text"],
];

let chosenArray = [];

function elaborate(event) {
  let values = event.currentTarget.value.split('-');
  let chosenValue = myArray.find(findInTheArray.bind(null, values));
  // check that you already didn't add the selected value. To remove if you 
  // want duplicates too
  let isChosenValueAlreadyPresent = chosenArray.find(findInTheArray.bind(null, values));
  if (chosenValue && !isChosenValueAlreadyPresent) {
    chosenArray.push(chosenValue);
  }
  console.log(chosenArray);
}

function findInTheArray(values, el) {
  let ret = false;
  values.forEach(val => {
    if (el[0].indexOf(val) > -1) {
      ret = true;
    }
  });
  return ret;
}
<select onchange="elaborate(event)">
  <option value="8-17">8-17</option>
  <option value="9-17">9-17</option>
</select>