Monday, 15 July 2013

jquery - Is there a function to find subarray in javascript with repeated elements? -



jquery - Is there a function to find subarray in javascript with repeated elements? -

i writing javascript filter out arrays contains specific sub-array. of course of study can write function myself, curious if there built-in function in javascript or other javascript library that, or if there easy way few lines.

i found can utilize underscore.js if elements in sub-array unique. there intersection function , can check lenght after intersection see if length correct. however, function fails if there repeated values in sub-array.

for example,

_.intersection([1, 2, 3, 4, 5], [2, 1]);

this homecoming [1, 2] , checking length know array contains sub-array.

however, when there repeated values in sub-array,

_.intersection([1, 1, 2, 3, 4, 7, 10], [1, 1, 2]); _.intersection([1, 2, 3, 4], [1, 1, 2]);

both homecoming [1, 2] , cases cannot distinguished.

is there other pre-built function can utilize or there easy way job within few lines?

try this:

function contains(a, b) { // sort arguments if(a.length < b.length) { var temp = a; = b; b = temp; } // re-create array = a.slice(); homecoming b.every(function(elm) { var index = a.indexof(elm); if(index !== -1) { // remove found element a.splice(index, 1); homecoming true; } homecoming false; }); } console.log(contains([1, 1, 2], [1, 2, 3, 4, 7, 10])); // logs false console.log(contains([1, 1, 2], [1, 1, 2, 3, 4, 7, 10])); // logs true console.log(contains([1, 2, 3, 4, 7, 10], [1, 1, 2])); // logs false console.log(contains([1, 1, 2, 3, 4, 7, 10], [1, 1, 2])); // logs true

here demo

javascript jquery arrays sub-array

No comments:

Post a Comment