Multiple array intersection in javascript - javascript

How to write in javascript(w/wth JQuery) to find values that intersect between arrays?
It should be like
var a = [1,2,3]
var b = [2,4,5]
var c = [2,3,6]
and the intersect function should returns array with value {2}. If possible it could applicable for any number of arrays.
Thanks

There are many ways to achieve this.
Since you are using jQuery I will suggest use grep function to filter the value that are present in all three array.
var a = [1, 2, 3]
var b = [2, 4, 5]
var c = [2, 3, 6]
var result = $.grep(a, function(value, index) {
return b.indexOf(value) > -1 && c.indexOf(value) > -1;
})
console.log(result)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Explanation: Loop over any array and filter out the values that are present in other array.
Update (for multimidensional array):
Concept - flatten the multidimensional array that is transform [[1,2],3,4] to [1,2,3,4] and then use the same logic used for single dimensional array.
Example:
var a = [
[1, 4], 2, 3
]
var b = [2, 4, 5]
var c = [2, 3, 6, [4, 7]]
//flatten the array's
//[1,4,2,3]
var aFlattened = $.map(a, function(n) {
return n;
})
//[2,4,5]
var bFlattened = $.map(b, function(n) {
return n;
})
//[2,3,6,4,7]
var cFlattened = $.map(c, function(n) {
return n;
})
var result = $.grep(aFlattened, function(value) {
return (bFlattened.indexOf(value) > -1 && cFlattened.indexOf(value) > -1);
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

// First this is how you declare an array
var a = [1,2,3];
var b = [2,4,5];
var c = [2,3,6];
// Second, this function should handle undetermined number of parameters (so arguments should be used)
function intersect(){
var args = arguments;
// if no array is passed then return empty array
if(args.length == 0) return [];
// for optimisation lets find the smallest array
var imin = 0;
for(var i = 1; i < args.length; i++)
if(args[i].length < args[imin].length) imin = i;
var smallest = Array.prototype.splice.call(args, imin, 1)[0];
return smallest.reduce(function(a, e){
for(var i = 0; i < args.length; i++)
if(args[i].indexOf(e) == -1) return a;
a.push(e);
return a;
}, []);
}
console.log(intersect(a, b, c));

First of all '{}' means Object in JavaScript.
Here is my suggestion.(this is another way of doing it)
// declarations
var a = [1,2,3];
var b = [2,4,5];
var c = [2,3,6];
// filter property of array
a.filter(function(val) {
if (b.indexOf(val) > -1 && c.indexOf(val) > -1)
return val;
});
what it does is it checks for each element in array 'a' and checks if that value is present in array 'b' and array 'c'. If it is true it returns the value. Simple!!!. The above code should work for String as well but it wouldn't work for IE < 9, so be careful.

// Intersecting 2 ordered lists of length n and m is O(n+m)
// This can be sped up by skipping elements
// The stepsize is determined by the ratio of lengths of the lists
// The skipped elements need to be checked after skipping some elements:
// In the case of step size 2 : Check the previous element
// In case step size>2 : Binary search the previously skipped range
// This results in the best case complexity of O(n+n), if n<m
// or the more propable complexity of O(n+n+n*log2(m/n)), if n<m
function binarySearch(array, value, start = 0, end = array.length) {
var j = start,
length = end;
while (j < length) {
var i = (length + j - 1) >> 1; // move the pointer to
if (value > array[i])
j = i + 1;
else if (value < array[i])
length = i;
else
return i;
}
return -1;
}
function intersect2OrderedSets(a, b) {
var j = 0;
var k = 0;
var ratio = ~~(b.length / a.length) - 1 || 1;
var result = [];
var index;
switch (ratio) {
case 1:
while (j < a.length) {
if (a[j] === b[k]) {
result.push(a[j]);
j++;
k++;
} else if (a[j] < b[k]) {
while (a[j] < b[k]) j++;
} else {
while (b[k] < a[j]) k++;
if (k >= b.length) break;
}
}
break;
case 2:
while (j < a.length) {
if (a[j] === b[k]) {
result.push(a[j]);
j++;
k++;
} else if (a[j] < b[k]) {
while (a[j] < b[k]) j++;
} else {
while (b[k] < a[j]) k += 2;
if (k - 1 >= b.length) break;
if (a[j] <= b[k - 1]) k--;
}
}
break;
default:
while (j < a.length) {
if (a[j] === b[k]) {
result.push(a[j]);
j++;
k++;
} else if (a[j] < b[k]) {
while (a[j] < b[k]) j++;
} else {
while (b[k] < a[j]) k += ratio;
index = binarySearch(b, a[j], k - ratio + 1, k + 1 < b.length ? k + 1 : b.length - 1);
if (index > -1) {
result.push(a[j]);
j++;
k = index + 1;
} else {
j++;
k = k - ratio + 1;
}
if (k >= b.length) break;
}
}
}
return result;
}
function intersectOrderedSets() {
var shortest = 0;
for (var i = 1; i < arguments.length; i++)
if (arguments[i].length < arguments[shortest].length) shortest = i;
var result = arguments[shortest];
for (var i = 0, a, b, j, k, ratio, index; i < arguments.length; i++) {
if (result.length === 0) return result;
if (i === shortest) continue;
a = result;
b = arguments[i];
result = intersect2OrderedSets(a, b);
}
return result;
}
How to use:
intersectOrderedSets(a,b,c);

Related

Find largest d in array such that a + b + c = d

Task
You are given a sorted integer array arr. It contains several unique integers(negative, positive, or zero).
Your task is to find the largest d such that a + b + c = d, where a, b, c, and d are distinct elements of arr. If no such an element d found, return null.
Example:
For arr = [2,3,5,7,12], the output should be 12 (this array passes my function correctly)
For arr = [-100,-1,0,7,101], the output should be 0 (this one does not pass)
I could manage the positive numbers check but my function miserably fails with negatives
function findD(arr) {
myArr = arr.sort((a, b) => b - a);
for (var i = 0; i < myArr.length; i++) {
for (var k = i + 1; k < myArr.length - 2; k++) {
var j = k + 1,
d = myArr.length - 1;
while (j < d) {
let sum = myArr[k] + myArr[j] + myArr[d];
if (sum == myArr[i]) {
return myArr[i];
} else if (sum < myArr[i]) {
d--;
} else if (sum > myArr[i]) {
j++;
}
}
}
}
return null
}
how to handle negative values in the array?
Let's imagine there's an array like [-2, -1, 0, 3].
Then, after sorting it in the descending order as per your algorithm it will be [3, 0, -1, -2]. Obviously, your algorithm will pick only 3 as you assume d must be larger than numbers at the remaining 3 positions. That's wrong, of course. You shouldn't assume that a, b and c are necessarily less than d. That's why you must check other cases when d occupies all possible positions in relation to a,b,c. So, first consider a brute force approach that will have O(n^4) time and O(1) space complexity:
...
for (var i = myArr.length; i >= 0 ; i--) {
for (var k = 0; k < myArr.length; k++) {
if (k == i) {
continue
}
for (var j = k + 1; j < myArr.length; j++) {
if (j == i) {
continue
}
for (var d = j + 1; d < myArr.length; d++) {
if (d == i) {
continue
}
if (myArr[i] == myArr[k] + myArr[j] + myArr[d]) {
return myArr[i]
}
}
}
}
}
return null
...
But this problem can be solved in O(n^2) time and O(n^2) space.
First we should realise that a + b = d - c.
So, for the given array arr and every pair of indices i,j: i<j we store arr[i] + arr[j] (a + b) as a key and pair i,j as an item of a value (the value is a list of pairs of indices) in sumsMap. The value must be a list because there can be several pairs of indices corresponding to the same sum a + b.
Then, go through each pair of indices again k,l and check if a key arr[l] - arr[k] (d - c) or arr[k] - arr[l] (c - d) exists in sumsMap. If it does and indices l,k are different from the ones in sumsMap[s] then update the maximum element if it's lower than arr[l].
function solve(arr) {
var sumsMap = {}
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
var sum = arr[i] + arr[j]
// several pairs of indices can correspond to the same summ so keep all of them
var mappedIndices = sumsMap[sum]
if (typeof mappedIndices == "undefined") {
mappedIndices = []
}
let pair = {}
pair.first = i
pair.second = j
mappedIndices.push(pair)
sumsMap[sum] = mappedIndices
}
}
var maxD = Number.MIN_SAFE_INTEGER
for (var k = 0; k < arr.length; k++) {
for (var l = 0; l < arr.length; l++) {
mappedIndices = sumsMap[arr[l] - arr[k]]
if (mappedIndices != undefined) {
// in the worst case, 4 pairs of indices may contain k or l but the fifth one won't as numbers in the array are unique and hence the same index can occur only twice
var steps = Math.min(5, mappedIndices.length)
for (var s = 0; s < steps; s++) {
var pair = mappedIndices[s]
if (pair.first != k && pair.first != l && pair.second != k && pair.second != l) {
maxD = Math.max(maxD, arr[l])
}
}
}
}
}
if (maxD == Number.MIN_VALUE) {
return -1
} else {
return maxD
}
}
document.write(solve([-100,-1,0,7,101] ))
document.write("<br>")
document.write(solve([-93,-30,-31,-32] ))
I translated the function Renaldo suggested from https://www.geeksforgeeks.org/find-largest-d-in-array-such-that-a-b-c-d/ to JavaScript for you.
function findLargestd(S, n){
var found = false;
// sort the array in
// ascending order
S.sort((a, b) => a - b);
// iterating from backwards to
// find the required largest d
for(var i = n - 1; i >= 0; i--){
for(var j = 0; j < n; j++){
// since all four a, b, c,
// d should be distinct
if(i == j){
continue;
}
for(var k = j + 1; k < n; k++){
if(i == k){
continue;
}
for(var l = k + 1; l < n; l++){
if(i == l){
continue;
}
// if the current combination
// of j, k, l in the set is
// equal to S[i] return this
// value as this would be the
// largest d since we are
// iterating in descending order
if(S[i] == S[j] + S[k] + S[l]){
found = true;
return S[i];
}
}
}
}
}
//if not found, return 0
if(found === false){
return 0;
}
}

Correct merge sort

So... If I input:
4 1 5 3
INSTEAD OF 1,3,4,5
I GET [ 4, 1, 5, 3 ]
Following is the code for merge sort but for the last comparison the program doesn't fetch updated (1,4) (3,5) value rather (4,1) (5,3) thus giving the wrong result.
var a = [4, 1, 5, 3];
q(a);
function q(a) {
var start = 0;
var n = a.length;
var length = parseInt(n / 2);
if (n < 2) {
return n;
}
var l = [], r = [];
for (i = 0; i < length; i++) {
l[i] = a[i]; //left array
}
for (i = 0, j = length; j < n; i++ , j++) {
r[i] = a[j]; //right array
}
q(l); //merge sort left array
q(r); //merge sort right array
comp(l, r);
}
function comp(l, r) {
var k = [], m = 0, i = 0, j = 0;
while (i < ((l.length)) && j < ((r.length))) {
if (l[i] < r[j]) {
k[m] = l[i];
i++;
m++
}
else {
k[m] = r[j];
j++;
m++
}
}
while (i != (l.length)) {
k[m] = l[i];
m++;
i++;
}
while (j != (r.length)) {
k[m] = r[j];
m++;
j++;
}
console.log(k); //for final output it is [ 4, 1, 5, 3 ] instead of [1,3,4,5]
}
You have a couple small problems. The main one is that you are returning the wrong thing from your edge condition:
if (n < 2) {
return n; // n is just a length; doesn't make sense to return it.
}
n is the length, you really want to return the small array here:
if (n < 2) {
return a; // return the array instead
}
Also, you need to pass the result of the recursive call to your comp function. Right now you're just returning the original lists with:
comp(l, r)
Something like this would work better:
let l_sort = q(l); //merge sort left array
let r_sort = q(r); //merge sort right array
return comp(l_sort, r_sort); // merge the arrays when recursion unwinds.
And you need to return things for recursion to work.
Put all together:
function q(a) {
var start = 0;
var n = a.length;
var length = parseInt(n / 2);
if (n < 2) {
return a;
}
var l = [],
r = [];
for (i = 0; i < length; i++) {
l[i] = a[i]; //left array
}
for (i = 0, j = length; j < n; i++, j++) {
r[i] = a[j]; //right array
}
let l_sort = q(l); //merge sort left array
let r_sort = q(r); //merge sort right array
return comp(l_sort, r_sort);
}
function comp(l, r) {
var k = [],
m = 0,
i = 0,
j = 0;
while (i < ((l.length)) && j < ((r.length))) {
if (l[i] < r[j]) {
k[m] = l[i];
i++;
m++
} else {
k[m] = r[j];
j++;
m++
}
}
while (i != (l.length)) {
k[m] = l[i];
m++;
i++;
}
while (j != (r.length)) {
k[m] = r[j];
m++;
j++;
}
return k
}
console.log(q([4, 1, 5, 3]).join(','));
console.log(q([5, 4, 3, 2, 1]).join(','));
console.log(q([2, 3]).join(','));
console.log(q([3, 2]).join(','));
console.log(q([1]).join(','));

What is the best way to shift a multidimensional array in Javascript?

I'm trying to create a javascript function that shifts an array right x units any up y units. It must keep the array size the same, and it must call unloadChunk for elements that are getting shifted off the multidimensional array. Here is my current implementation:
function shift(x, y) {
if (x > 0) {
for (var i = 0; i < chunks.length; i++) {
for (var j = chunks[i].length - 1; j >= 0; j--) {
if(j + x > chunks[i].length - 1 && chunks[i][j]) {
unloadChunk(i, j);
}
if (j < x) {
chunks[i][j] = null;
}
else {
chunks[i][j] = chunks[i][j - x];
}
}
}
}
else if (x < 0) {
for (var i = 0; i < chunks.length; i++) {
for (var j = 0; j < chunks[i].length; j++) {
if(j + x < 0 && chunks[i][j]) {
unloadChunk(i, j);
}
if (j - x >= chunks[i].length) {
chunks[i][j] = null;
}
else {
chunks[i][j] = chunks[i][j - x];
}
}
}
}
if (y > 0) {
for (var i = 0; i < chunks.length; i++) {
if (i + y >= chunks.length) {
for (var j = 0; j < chunks.length; j++) {
if(i - y < 0 && chunks[i][j]) {
unloadChunk(i, j);
}
chunks[i][j] = null;
}
}
else {
for (var j = 0; j < chunks.length; j++) {
if(i - y < 0 && chunks[i][j]) {
unloadChunk(i, j);
}
chunks[i][j] = chunks[i + y][j];
}
}
}
}
else if (y < 0) {
for (var i = chunks.length - 1; i >= 0; i--) {
if (i + y < 0) {
for (var j = 0; j < chunks.length; j++) {
if(i - y > chunks.length - 1 && chunks[i][j]) {
unloadChunk(i, j);
}
chunks[i][j] = null;
}
}
else {
for (var j = 0; j < chunks.length; j++) {
if(i - y > chunks.length - 1 && chunks[i][j]) {
unloadChunk(i, j);
}
chunks[i][j] = chunks[i + y][j];
}
}
}
}
}
If you're having trouble understanding exactly what I want the shift function to do, take a look at this fiddle and look at the html output.
My attempt at creating the shift function works, but it has 10 for loops. My question was, is there a more efficient, less verbose way to do this?
This proposal uses
Array#forEach: visit each item
Array#map: return value for each item
Array#pop: removes and return last element
Array#push: adds one or more elements at the end
Array#shift: removes and return first element
Array#unshift: adds one or more elements at the beginning
For better visibillity, I replaced the null value with 1000, 2000, 3000 and 4000.
function shift(x, y) {
while (x > 0) {
chunks.forEach(function (a) {
a.pop();
a.unshift(1000);
});
x--;
}
while (x < 0) {
chunks.forEach(function (a) {
a.shift();
a.push(2000);
});
x++;
}
while (y > 0) {
chunks.unshift(chunks.pop().map(function () { return 3000; }));
y--;
}
while (y < 0) {
chunks.push(chunks.shift().map(function () { return 4000; }));
y++;
}
}
function print(msg) {
document.body.innerHTML += '<p>' + msg + '</p>';
}
function printarr(arr) {
for (var i = 0; i < arr.length; i++) {
print(JSON.stringify(arr[i]))
}
}
var chunks = [[5, 3, 1], [9, 2, 5], [2, 3, 7]];
print("chunks: " + JSON.stringify(chunks));
shift(1, 0);
print("shifting right 1. chunks: "); printarr(chunks);
shift(-1, 0);
print("shifting left 1. chunks: "); printarr(chunks);
shift(0, 1);
print("shifting up 1. chunks: "); printarr(chunks);
shift(0, -1);
print("shifting down 1. chunks: "); printarr(chunks);
You can use pop(), push(), shift(), unshift() Array methods
var chunks = [
[5, 3, 1],
[9, 2, 5],
[2, 3, 7]
];
function shiftDown(){
chuck.pop();
chuck.unshift(Array(3));
}
function shiftUp(){
chuck.shift();
chuck.push(Array(3));
}
function shiftRight(){
chuck.foreach(function(v){
v.pop();
v.unshift(null);
})
}
function shiftLeft(){
chuck.foreach(function(v){
v.shift();
v.push(null);
})
}
If interpret Question correctly, you can use Array.prototype.forEach(), Array.prototype.splice()
var chunks = [[5, 3, 1], [9, 2, 5], [2, 3, 7]];
// `x`: Index at which to start changing array
// `y`: An integer indicating the number of old array elements to remove
function shift(arr, x, y, replacement) {
arr.forEach(function(curr, index) {
// The elements to add to the array, beginning at the start index.
// start index: `x`
curr.splice(x, y, replacement)
});
return arr
}
// e.g.,
shift(chunks, -1, 1, null);
console.log(chunks);
it must call unloadChunk for elements that should be set to null
it's not a good idea to mutate an Array, while you're iterating over the same Array. So change unloadChunk() to not change chunks, but return the new value.
in my case I'm filling all the null values with new values.
then why do you bother to insert the null-values in the first place? why don't you just insert the new values?
//one-dimensional shift
function shift(arr, offset, callback){
var i, j, len = arr.length;
if(len && (offset |= 0)){
typeof callback === "function" || (callback = function(v){return v});
if(offset < 0){
for(i=-offset,j=0; i<len;)arr[j++]=arr[i++];
while(j<len)arr[j]=callback(null,j++,arr);
}else if(offset){
for(i=len-offset,j=len; i>0;)arr[--j]=arr[--i];
for(i=0; i<j;++i)arr[i]=callback(null,i,arr);
}
}
return arr;
}
//two dimensional shift
function shift2d(matrix, offsetX, offsetY, callback){
var i, len = matrix.length, tmp, fn;
offsetY |= 0;
offsetX |= 0;
if(len && matrix[0].length && (offsetY || offsetX)){
typeof callback === "function" || (callback = function(v){return v});
fn = function(val,j){ return callback(null, [i,j], matrix) };
tmp = {length: matrix[0].length};
offsetY && shift(matrix, offsetY, function(){return tmp});
for(i = 0; i < len; ++i){
if(matrix[i] === tmp){
matrix[i] = Array.from(tmp,fn);
}else{
shift(matrix[i], offsetX, fn);
}
}
}
return matrix;
}
and the code:
var chunks = [[5, 3, 1], [9, 2, 5], [2, 3, 7]];
console.log(chunks);
console.log(shift2d(chunks, -1, 1));
console.log(shift2d(chunks, 1, -1, computeValue));
function computeValue(value, index, array){
console.log("value: %o index: %o, is chunks: %o", value, index, array === chunks);
//return the new value for this field
return JSON.stringify(index);
return Math.random();
//with ES6 array destructuring:
var [row,col] = index;
return row*3 + col;
}
shift() and shift2d() expect as the last argument an (optional) callback function that returns the new values.
For consistency reasons, I pass the same argument as Array.map and the others
value: always null, only there for consistency reasons
index: the "index" that is accessed. For shift2d this is an array of indices (take a look at array destructuring)
array: the current array/matrix. Don't mess around with this while it gets changed. The main reason to pass this argument, is to check wich Array you're currently processing.

finding prime numbers in an array from 1-200

A math problem describes a list of numbers from 1-200, you must skip the number 1, and then for each number that follows, remove all multiples of that number from the list. Do this until you have reached the end of the list.
Here's what I have so far.
var x = []; // creating an array called x with zero numbers
for ( var i = 1; i <= 200; i++ ){
x.push(i);
};
// x now should have an array that contains the intergers from 1-200.
//looping through the array.
for ( var i = 0; i <= x.length; i++ ){ //going from 1-200
if (x[i] == 1){
continue; // skipping 1
} else {
for ( var n = i+1; n <= i; n++){ // take the number 1 index bigger than x[i]
if ( n % i == 0){ //find if the modulus of x[n] and x[i] is zeor, meaning it is divisible by x[i]
x.shift(); //remove that number
console.log(x[n]);
} else {
continue;
}
}
}
};
Instead of adding number 1 to 200 and then removing non prime numbers, try only putting prime numbers into that list. Since this is a school problem (I'm guessing) I don't want to give you the answer, but if you have more questions I can answer.
Also your nested loop will never run, go over that logic again.
Another version (a minute too late, as always ;-), one with comments
// lil' helper
function nextSet(a,n){
while(a[n] == 0) n++;
return n;
}
function setPrimes(a,n){
var k, j, r;
n = n + 1;
k = n;
while(k--)a[k] = 1;
a[0] = 0; // number 0
a[1] = 0; // number 1
// get rid of all even numbers
for(k = 4; k < n; k += 2) {
a[k] = 0;
}
// we don't need to check all of the numbers
// because sqrt(x)^2 = x
r = Math.floor(Math.sqrt(n));
k = 0;
while(k < n){
k = nextSet(a,k+1);
// a test if we had them all
if(k > r){
break;
}
// unmark all composites
for(j = k * k; j < n; j += 2*k){
a[j] = 0;
}
}
return a;
}
function getPrimes(n){
// we know the size of the input
var primearray = new Array(n);
// we don't know the size of the output
// prime-counting is still an unsolved problem
var output = [];
setPrimes(primearray, n);
for(var i = 0; i < n; i++){
if(primearray[i] == 1){
output.push(i);
}
}
return output;
}
getPrimes(200);
You can go through a full implementation of that algorithm at another primesieve.
Here is, I believe, a working example of what you want:
function isPrime(num){
if(num < 2){
return false;
}
for(var i=2,l=Math.sqrt(num); i<=l; i++){
if(num % i === 0){
return false;
}
}
return true;
}
function range(f, t){
for(var i=f,r=[]; i<=t; i++){
r.push(i);
}
return r;
}
function primeRange(from, to){
var a = range(from, to), r = [];
for(var i=0,l=a.length; i<l; i++){
var v = a[i];
if(isPrime(v)){
r.push(v);
}
}
return r;
}
var prmRng = primeRange(1, 200);
console.log(prmRng);
I solved it this way:
let numbers = new Array();
for (let i = 1; i <= 200; i++) {
numbers.push(i);
}
let primeNumbers = (num) => {
let prime = new Array();
for(let i = 0; i < num.length; i++) {
let count = 0;
for (let p = 2; p <= num[i]; p++) {
if(num[i] % p === 0 && num[i] !== 2) {
count++;
} else {
if(num[i] === 2 || count === 0 && num[i]-1 === p) {
prime[i] = num[i];
}
}
}
}
return prime.filter(Boolean);
}
console.log(primeNumbers(numbers));

How to compare two arrays in JavaScript?

If I have two arrays as parameters how can I find the starting index where the second parameter occurs as a sub-array in the array given as the first parameter.
E.g.: [5,9,3,6,8], [3,6] should return 2.
Is there a function in JavaScript for this, or does it just loop through both of them and compare?
findArrayInArray = function(a, b) {
var ai = a.length
, bi = b.length;
for(var i=0; i<ai; i++) {
if (a[i] === b[0]) {
if(bi === 1) return i;
for(var x=1; x<bi; x++) {
if(a[i+x] === b[x]) {
if(x === bi-1) return i;
} else {
break;
}
}
}
}
}
var arr1 = [5,9,3,6,8];
var arr2 = [3,6];
console.log(findArrayInArray(arr1,arr2)); // 2
http://jsfiddle.net/ymC8y/3/
In direct answer to your question, there is no built in function in JS to look in an array for a sub-array.
You will have to do some sort of brute force looping search like this or use some external library function that already has array comparison logic. Here's what a brute force solution in plain JS looks like:
function findSubArrayIndex(master, sub) {
for (var m = 0; m < master.length - sub.length + 1; m++) {
for (var s = 0; s < sub.length; s++) {
if (master[m + s] !== sub[s]) {
break;
} else if (s === sub.length - 1) {
return m;
}
}
}
return -1;
}
Working demo: http://jsfiddle.net/jfriend00/mt8WG/
FYI, here's a somewhat performance optimized version of this function:
function findSubArrayIndex(master, sub) {
var subLen = sub.length, subFirst, m, mlen;
if (subLen > 1) {
subFirst = sub[0];
for (m = 0, mlen = master.length - subLen + 1; m < mlen; m++) {
if (master[m] === subFirst) {
for (var s = 1; s < subLen; s++) {
if (master[m + s] !== sub[s]) {
break;
} else if (s === subLen - 1) {
return m;
}
}
}
}
} else if (subLen === 1) {
subFirst = sub[0];
for (m = 0, mlen = master.length; m < mlen; m++) {
if (master[m] === subFirst) {
return m;
}
}
}
return -1;
}
Working demo: http://jsfiddle.net/jfriend00/CGPtX/
function index (a, b) {
var as = new String(a),
bs = new String(b),
matchIndex = as.indexOf(bs);
if (matchIndex === -1) {
return -1;
} else if (matchIndex === 0) {
return 0;
}
return as.substring(0, matchIndex + 1).match(/,/g).length;
}
console.log(index([5,9,3,6,8], [3, 6]));
Try this - You loop through both arrays and compare each element:
var arr1 = [5,9,3,6,8];
var arr2 = [3,6];
findArrayInArray = function(arr1, arr2) {
for(var i=0; i<arr1.length; i++) {
for(var j=0; j<arr2.length; j++){
if(arr1[i] === arr2[j]){
return i;
}
}
}
return false;
}
findArrayInArray(arr1, arr2);

Categories

Resources