How can I find a string in a two dimensional array?

青春壹個敷衍的年華 提交于 2021-02-11 17:50:42

问题


I have an array that looks like this.

var array[["a","b"],["c","d"],["e","f"]];         

I want to be able to search through the array for the string "d" and return the corresponding value "c".


回答1:


try:

function find_str(array){
  for(var i in array){
    if(array[i][1] == 'd'){
      return array[i][0];
    }
  }
}

EDIT:

function find_str(array){
  for(var i=0;i<array.length;i++){
    if(array[i][1] == 'd'){
      return array[i][0];
    }
  }
}



回答2:


A general function for getting all the elements of the arrays that contain the specified value. The following function uses several methods of Array.prototype: filter, indexOf, map, slice, splice and concat for flattening the arrays.

var array = [["a","b"],["c","d"],["c","e","f"]];   

function findBy(arr, val) {
    var ret = arr.filter(function(el) {
        return el.indexOf(val) > -1;
    }).map(function(el) {
       var res = el.slice();
       res.splice(el.indexOf(val), 1);
       return res;
    });
    return Array.prototype.concat.apply([], ret);
}

findBy(array, 'c');
// -> ["d", "e", "f"]
findBy(array, 'b');
// -> ["a"]
findBy(array, 'g');
// -> []


来源:https://stackoverflow.com/questions/30228691/how-can-i-find-a-string-in-a-two-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!