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

javascript - How can I find a string in a two dimensional array? - Stack Overflow

programmeradmin3浏览0评论

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".

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".

Share Improve this question edited May 14, 2015 at 3:25 Dyrandz Famador 4,5255 gold badges27 silver badges40 bronze badges asked May 14, 2015 at 3:22 GoeffGoeff 411 silver badge3 bronze badges 11
  • Will you always be matching against the second element of a two-element subarray? – Greg Hewgill Commented May 14, 2015 at 3:25
  • you can create a loop then find the string on the first dimension – Dyrandz Famador Commented May 14, 2015 at 3:25
  • The "search" criterion is not clear. – Ram Commented May 14, 2015 at 3:25
  • [["a","b"],["c","d"],["e","f"]].filter(function(a){return a[1]==this}, "d")[0][0] – dandavis Commented May 14, 2015 at 3:28
  • I have tried the find mand and a number of iterative processes but I cannot separate the two elements of each item to query. – Goeff Commented May 14, 2015 at 3:29
 |  Show 6 more ments

2 Answers 2

Reset to default 3

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];
    }
  }
}

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');
// -> []
发布评论

评论列表(0)

  1. 暂无评论