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

javascript - How to check if a two dimensional array includes a string? - Stack Overflow

programmeradmin5浏览0评论

I have a two dimensional array arr[cols][rows]. I want to know if the cols contains a string "hello". How can I check that using .includes("hello") method.

Please note that I am trying to check this inside a loop with counter i. So I have to do something like arr[i][0].includes("hello");

I have a two dimensional array arr[cols][rows]. I want to know if the cols contains a string "hello". How can I check that using .includes("hello") method.

Please note that I am trying to check this inside a loop with counter i. So I have to do something like arr[i][0].includes("hello");

Share Improve this question asked Jan 31, 2018 at 8:58 DarthWaderDarthWader 1,0361 gold badge10 silver badges18 bronze badges 4
  • 2 and did you do that? what do you get? – Nina Scholz Commented Jan 31, 2018 at 9:00
  • I assume you want to know if [col] contained "hello" in any of the [row]? You add a flag in your j loop (assuming you used i for col and j for row.) – Adelin Commented Jan 31, 2018 at 9:01
  • Add more info such as - does sub-arrays have uniform length? How many dimensions have to be supported? – gurvinder372 Commented Jan 31, 2018 at 9:07
  • Yes, sub-arrays have uniform length. 2 dimensions have to be supported which means, there is an array that contains arrays which in turn contains two items each. – DarthWader Commented Feb 1, 2018 at 15:22
Add a comment  | 

1 Answer 1

Reset to default 21

You can use array.prototype.some along with array.prototype.includes. It shoud be:

var datas= [
  ["aaa", "bbb"],
  ["ddd", "eee"]
];

function exists(arr, search) {
    return arr.some(row => row.includes(search));
}

console.log(exists(datas, 'ddd'));
console.log(exists(datas, 'xxx'));

发布评论

评论列表(0)

  1. 暂无评论