简体   繁体   English

javascript 搜索 arrays 的数组

[英]javascript search array of arrays

Let's say we have the following js array假设我们有以下 js 数组

var ar = [
   [2,6,89,45],
   [3,566,23,79],
   [434,677,9,23]
];

var val = [3,566,23,79];

Is there a js builtin function or jQuery one with which you can search the array ar for val ?是否有内置 function 或 jQuery 的 js,您可以使用它在数组ar中搜索val

Thanks谢谢

** * UPDATE * ** * ** * ** * ** * ** *更新* ** * ** * ** * ** *

Taking fusion's response I created this prototype根据Fusion 的回应,我创建了这个原型

Array.prototype.containsArray = function(val) {
    var hash = {};
    for(var i=0; i<this.length; i++) {
        hash[this[i]] = i;
    }
    return hash.hasOwnProperty(val);
}

you could create a hash.你可以创建一个 hash。

var ar = [
    [2,6,89,45],
    [3,566,23,79],
    [434,677,9,23]
];

var hash = {};
for(var i = 0 ; i < ar.length; i += 1) {
    hash[ar[i]] = i;
}

var val = [434,677,9,23];

if(hash.hasOwnProperty(val)) {
    document.write(hash[val]);
}

You can also use a trick with JSON serializing.您还可以使用 JSON 序列化的技巧。 It is short and simple, but kind of hacky.它简短而简单,但有点hacky。
It works, because "[0,1]" === "[0,1]" .它有效,因为"[0,1]" === "[0,1]"

Here is the working demo snippet:这是工作演示片段:

 Array.prototype.indexOfForArrays = function(search) { var searchJson = JSON.stringify(search); // "[3,566,23,79]" var arrJson = this.map(JSON.stringify); // ["[2,6,89,45]", "[3,566,23,79]", "[434,677,9,23]"] return arrJson.indexOf(searchJson); }; var arr = [ [2,6,89,45], [3,566,23,79], [434,677,9,23] ]; document.body.innerText = arr.indexOfForArrays([3,566,23,79]);

function indexOfArray(val, array) {
  var hash = {};
  for (var i = 0; i < array.length; i++) {
    hash[array[i]] = i;
  }
  return (hash.hasOwnProperty(val)) ? hash[val] : -1;
};

I consider this more useful for than containsArray() .我认为这比containsArray()更有用。 It solves the same problem (using a hash table ) but returns the index (rather than only boolean true / false ).它解决了同样的问题(使用hash 表)但返回索引(而不仅仅是 boolean true / false )。

Can you try this?你能试试这个吗?

var ar = [
   [2,6,89,45],
   [3,566,23,79],
   [434,677,9,23]
];

var val = [3,566,23,79];


var sval = val.join("");
for(var i in ar)
{
    var sar = ar[i].join("");
    if (sar==sval) 
    {
        alert("found!");
        break;
    }
}

Why don't you use javascript array functions?为什么不使用 javascript 数组函数?

function filterArrayByValues(array, values) {
            return array.filter(function (arrayItem) {
                return values.some(function (value) {
                    return value === arrayItem;
                });
            });
        }

Or if your array is more complicated, and you want compare only one property but as result return whole object:或者,如果您的数组更复杂,并且您只想比较一个属性,但结果返回整个 object:

  function filterArrayByValues(array, values, propertyName) {
            return array.filter(function (arrayItem) {
                return values.some(function (value) {
                    return value === arrayItem[propertyName];
                });
            });
        }

More about used functions: filter() and some()更多关于使用的函数: filter()some()

You can use Array.prototype.some() , Array.prototype.every() to check each element of each array.您可以使用Array.prototype.some()Array.prototype.every()来检查每个数组的每个元素。

 var ar = [ [2, 6, 89, 45], [3, 566, 23, 79], [434, 677, 9, 23] ]; var val = [3, 566, 23, 79]; var bool = ar.some(function(arr) { return arr.every(function(prop, index) { return val[index] === prop }) }); console.log(bool);

I guess there is no such JS functionality available.我想没有这样的 JS 功能可用。 but you can create one但你可以创建一个

function arrEquals( one, two )
{
    if( one.length != two.length )
    {
        return false;
    }
    for( i = 0; i < one.length; i++ )
    {
        if( one[i] != two[i] )
        {
            return false;
        }
    }
    return true;
}

The problem with this is that of object/array equality in Javascript.问题在于 Javascript 中的对象/数组相等。 Essentially, the problem is that two arrays are not equal, even if they have the same values.本质上,问题在于两个 arrays 不相等,即使它们具有相同的值。 You need to loop through the array and compare the members to your search key ( val ), but you'll need a way of accurately comparing arrays.您需要遍历数组并将成员与您的搜索键 ( val ) 进行比较,但您需要一种准确比较 arrays 的方法。

The easiest way round this is to use a library that allows array/object comparison.最简单的方法是使用允许数组/对象比较的库。 underscore.js has a very attractive method to do this: underscore.js有一个非常有吸引力的方法来做到这一点:

for (var i = 0; i < ar.length; i++) {
    if (_.isEqual(ar[i], val)) {
        // value is present
    }
}

If you don't want to use another library (though I would urge you to -- or at least borrow the message from the Underscore source), you could do this with JSON.stringify ...如果您不想使用另一个库(尽管我会敦促您使用 - 或者至少从 Underscore 来源借用消息),您可以使用JSON.stringify ...

var valJSON = JSON.stringify(val);
for (var i = 0; i < ar.length; i++) {
    if (valJSON === JSON.stringify(ar[i]) {
        // value is present
    }
}

This will almost certainly be significantly slower, however.然而,这几乎肯定会明显变慢。

You can use toString convertion to compare elements您可以使用 toString 转换来比较元素

var ar = [
   [2,6,89,45],
   [3,566,23,79],
   [434,677,9,23]
];

var val = [3,566,23,79];

s = !ar.every(a => (a.toString() != val.toString()));
console.log(s) // true

Use this instead改用这个

if (ar.join(".").indexOf(val) > -1) {
 return true;
} else {
 return false;
}

Use lodash isEqual使用 lodash isEqual

const isValIncludedInAr = ar.some(element => isEqual(element, val)) 

 const arrayOne = [2,6,89,45]; const arrayTwo = [3,566,23,79]; const arrayThree = [434,677,9,23]; const data = new Set([arrayOne, arrayTwo, arrayThree]); // Check array if exist console.log( data.has(arrayTwo) ); // It will return true. // If you want to make a set into array it's simple const arrayData = [...data]; console.log(arrayData); // It will return [[2,6,89,45], [3,566,23,79], [434,677,9,23]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM