How to compare two arrays in JavaScript? - 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);

Related

CodeWars sorting numbers and letters

I am currently doing a codewars problem, and I think I almost got it however, I ran across a problem when sorting index values with the same letter. link to problem is here. https://www.codewars.com/kata/5782dd86202c0e43410001f6
function doMath(s) {
let strSplit = s.split(' ');
let clonedArr = strSplit.slice();
for (let i = 0; i < strSplit.length; i++) {
for (let j = 0; j < strSplit[i].length; j++) {
let current = strSplit[i][j];
if (isNaN(current)) {
let letter = current;
strSplit[i] = strSplit[i].replace(letter, '');
strSplit[i] = letter + strSplit[i];
}
}
}
let sortedArr = strSplit.sort();
console.log(sortedArr);
// ["b900", "y369", "z123", "z246", "z89"]
let noLetterArr = sortedArr.map(x => {
return x.slice(1);
});
let numberArr = noLetterArr.map(y => {
return +y;
})
let firstEl = numberArr[0];
for (let i = 1; i < numberArr.length; i++) {
if (numberArr.indexOf(numberArr[i]) % 4 == 1) {
firstEl += numberArr[i];
}
if (numberArr.indexOf(numberArr[i]) % 4 == 2) {
firstEl -= numberArr[i];
}
if (numberArr.indexOf(numberArr[i]) % 4 == 3) {
firstEl *= numberArr[i];
}
}
return firstEl;
}
console.log(doMath('24z6 1z23 y369 89z 900b'));
I would like to sort the sortedArr the ones with the same letter by how they first appeared in string. So since "z246" appeared first in the original string. I would like to have that before "1z23". I had a hard time creating a function for that.
var al = [];
function doMath(s) {
var ar = s.split(" ");
for (let i = 0; i < ar.length; i++) {
for (let char of ar[i]) {
let temp = char.match(/[a-z]/i);
if (temp) {
al[i] = char;
ar[i] = ar[i].replace(char, '');
ar[i] = char + ar[i];
}
}
}
al = al.sort();
//New Sort Logic to pass above test case and others too
var n = [];
for (let i = 0; i < al.length; i++) {
for (let j = 0; j < ar.length; j++) {
if (ar[j].startsWith(al[i]) && !n.includes(ar[j])) {
n.push(ar[j]);
}
}
}
var result = parseInt(n[0].substr(1)),
count = 1;
for (let i = 1; i < n.length; i++) {
if (count == 1) {
result = result + parseInt(n[i].substr(1));
count++;
} else if (count == 2) {
result = result - parseInt(n[i].substr(1));
count++;
} else if (count == 3) {
result = result * parseInt(n[i].substr(1));
count++;
} else if (count == 4) {
result = result / parseInt(n[i].substr(1));
count = 1;
}
}
return Math.round(result);
}

CodeWars/ Merged String Checker

The challenge is next:
At a job interview, you are challenged to write an algorithm to check if a given string, s, can be formed from two other strings, part1 and part2.
The restriction is that the characters in part1 and part2 are in the same order as in s.
The interviewer gives you the following example and tells you to figure out the rest from the given test cases.
What am I doing wrong? Why it fails anyway?
I wrote 2 different scripts, and both aren't working for some test cases
function isMerge(s, part1, part2) {
var sArr = s.split('');
var part1Arr = part1.split('');
var part2Arr = part2.split('');
var tempArr = new Array(sArr.length);
function compareArrays(arr1, arr2){
var count = 0;
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) count++;
}
return (count == 0);
}
for (var i = 0; i < sArr.length; i++) {
for (var j = 0; j < part1Arr.length; j++) {
if (sArr[i] == part1Arr[j]) tempArr[i] = j;
}
for (var k = 0; k < part2Arr.length; k++) {
if (sArr[i] == part2Arr[k]) tempArr[i] = k;
}
}
alert(tempArr);
var check = tempArr.slice();
check.sort();
alert(check);
if (compareArrays(tempArr, check)) return true;
else return false;
}
alert(isMerge('codewars', 'cdw', 'oears'));
function isMerge(s, part1, part2) {
// create arrays of letters
var sArr = s.split('');
var part1Arr = part1.split('');
var part2Arr = part2.split('');
// create an associative array 'temp' (0:C, 1:O and so on)
var temp = {};
for (var k = 0; k < sArr.length; k++) {
temp[k] = sArr[k];
}
// reverse an associative array 'temp' (now C:0, O:0 and so on)
for (var key in temp) {
var keyTemp = key;
var keyValue = temp[key];
key = keyValue;
temp[key] = keyTemp;
}
// the function that compares arrays
function compareArrays(arr1, arr2){
var count = 0;
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) count++;
}
return (count == 0);
}
// sorting function
function order(a, b) {
var comparingA;
var comparingB;
for (var char in temp) {
if (char == a) {
comparingA = temp[char]; // comparingA is the number of 'a' in object 'temp'
}
if (char == b){
comparingB = temp[char]; // comparingB is the number of 'b' in object 'temp'
}
}
return (comparingA - comparingB);
}
// create copies of arrays
var part1Sorted = part1Arr.slice();
var part2Sorted = part2Arr.slice();
// and sort that copies
part1Sorted.sort(order);
part2Sorted.sort(order);
// If the array did not change after sorting, the order of the letters was correct
if (compareArrays(part1Sorted, part1Arr) && compareArrays(part2Sorted, part2Arr)) {
// so now we can check is merge possible
sArr = sArr.sort();
var parts = part1Arr.concat(part2Arr);
parts = parts.sort();
var res = compareArrays(sArr, parts);
return res;
}
return false;
}
alert(isMerge('codewars', 'code', 'wasr'));
alert(isMerge('codewars', 'oers', 'cdwa'));
I just added comments to the second script
I find it hard to understand what your code is attempting to do. It would help if you provided comments as well as explain the idea behind the algorithm/s you are attempting to implement.
Here's a commented example of a recursion that considers if pointers i and j to parts 1 & 2 could constitute a valid merge up to that point.
function isMerge(s, part1, part2) {
// Merge is invalid if the parts' lengths don't add up to the string's
if (part1.length + part2.length != s.length)
return false;
// Recursive function
function g(i, j){
// Base case: both pointers are exactly at the end of each part
if (i == part1.length && j == part2.length)
return true;
// One of our pointers has extended beyond the part's length,
// that couldn't be right
if (i > part1.length || j > part2.length)
return false;
// Just part1 matches here so increment i
if (part1[i] == s[i + j] && part2[j] != s[i + j])
return g(i + 1, j);
// Just part2 matches here so increment j
else if (part1[i] != s[i + j] && part2[j] == s[i + j])
return g(i, j + 1);
// Both parts match here so try incrementing either pointer
// to see if one of those solutions is correct
else if (part1[i] == s[i + j] && part2[j] == s[i + j])
return g(i + 1, j) || g(i, j + 1);
// Neither part matches here
return false;
}
// Call the recursive function
return g(0,0);
}
console.log(isMerge('codewars', 'cdw', 'oears'));
console.log(isMerge('codecoda', 'coda', 'code'));
console.log(isMerge('codewars', 'oers', 'cdwa'));
console.log(isMerge('codewars', 'cdw', 'years'));
Stack version for really long strings:
function isMerge2(s, part1, part2) {
if (part1.length + part2.length != s.length)
return false;
let stack = [[0,0]];
while (stack.length){
[i, j] = stack.pop();
if (i == part1.length && j == part2.length)
return true;
if (i > part1.length || j > part2.length)
continue;
if (part1[i] == s[i + j] && part2[j] != s[i + j])
stack.push([i + 1, j]);
else if (part1[i] != s[i + j] && part2[j] == s[i + j])
stack.push([i, j + 1]);
else if (part1[i] == s[i + j] && part2[j] == s[i + j]){
stack.push([i + 1, j]);
stack.push([i, j + 1]);
}
}
return false;
}
function test(){
let s = '';
for (let i=0; i<1000000; i++)
s += ['a','b','c','d','e','f','g'][~~(Math.random()*6)];
let lr = {
l: '',
r: ''
};
for (let i=0; i<s.length; i++){
let which = ['l', 'r'][~~(Math.random()*2)];
lr[which] += s[i];
}
console.log(isMerge2(s,lr.l,lr.r));
}
test();
This is a recursive approach: it checks for a match of the first character of the string with either of the parts, and if there's a match recurses to try and match the rest of the string with the rest of the parts. The tricky thing is that when the first character of both parts is the same, you have to check if you can match against either of them (this solves the Bananas test).
function isMerge(str, p1, p2) {
if (!str.length) return !p1.length && !p2.length;
if (p1.length && str.charAt(0) == p1.charAt(0)) {
if (p2.length && str.charAt(0) == p2.charAt(0)) {
return isMerge(str.substr(1), p1.substr(1), p2) || isMerge(str.substr(1), p1, p2.substr(1));
}
else {
return isMerge(str.substr(1), p1.substr(1), p2);
}
}
else if (p2.length && str.charAt(0) == p2.charAt(0)) {
return isMerge(str.substr(1), p1, p2.substr(1));
}
else {
return false;
}
}
Recursive Call:
You could use a recursive approach by first checking the length of string and part strings and then by the length or by checking a character and by checking the rest of the given part strings.
function isMerge(s, part1, part2) {
if (s.length !== part1.length + part2.length) {
return false;
}
if (!s.length) {
return true;
}
if (part1[0] === s[0] && isMerge(s.slice(1), part1.slice(1), part2)) {
return true;
}
if (part2[0] === s[0] && isMerge(s.slice(1), part1, part2.slice(1))) {
return true;
}
return false;
}
console.log(isMerge('codewars', 'cdw', 'oears')); // true
console.log(isMerge('codewars', 'oers', 'cdwa')); // true
console.log(isMerge('codecoda', 'coda', 'code')); // true
console.log(isMerge('baeabb', 'b', 'baeab')); // true
console.log(isMerge('bdab', 'bdab', '')); // true
console.log(isMerge('bfaef', 'f', 'bfae')); // true
console.log(isMerge('codewars', 'cdw', 'years')); // false
console.log(isMerge('codewars', 'code', 'warss')); // false
console.log(isMerge('codewars', 'codes', 'wars')); // false
console.log(isMerge('', 'a', 'b')); // false
.as-console-wrapper { max-height: 100% !important; top: 0; }
With a Stack instead of a Recursive Call:
function isMerge(s, part1, part2) {
var stack = [[s, part1, part2]];
if (s.length !== part1.length + part2.length) {
return false;
}
while (stack.length) {
[s, part1, part2] = stack.shift();
if (!s.length) {
return true;
}
if (part1[0] === s[0]) {
stack.push([s.slice(1), part1.slice(1), part2]);
}
if (part2[0] === s[0]) {
stack.push([s.slice(1), part1, part2.slice(1)]);
}
}
return false;
}
console.log(isMerge('codewars', 'cdw', 'oears')); // true
console.log(isMerge('codewars', 'oers', 'cdwa')); // true
console.log(isMerge('codecoda', 'coda', 'code')); // true
console.log(isMerge('baeabb', 'b', 'baeab')); // true
console.log(isMerge('bdab', 'bdab', '')); // true
console.log(isMerge('bfaef', 'f', 'bfae')); // true
console.log(isMerge('codewars', 'cdw', 'years')); // false
console.log(isMerge('codewars', 'code', 'warss')); // false
console.log(isMerge('codewars', 'codes', 'wars')); // false
console.log(isMerge('', 'a', 'b')); // false
.as-console-wrapper { max-height: 100% !important; top: 0; }
May you try this below?
function isMerge(s, part1, part2) {
var result= true;
var total = part1 + part2;
for (var i = 0; i < s.length; i++) {
var char = s.charAt(i);
if(total.indexOf(char) === -1) {
result = false;
break;
}
}
return result;
}
First of all, here is your code just working:
function isMerge(s, part1, part2) {
var sArr = s.split('');
var part1Arr = part1.split('');
var part2Arr = part2.split('');
var tempArr = new Array(sArr.length);
function compareArrays(arr1, arr2){
var count = 0;
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) count++;
}
return (count == 0);
}
for (var i = 0; i < sArr.length; i++) {
for (var j = 0; j < part1Arr.length; j++) {
if (sArr[i] == part1Arr[j]) tempArr[i] = part1Arr[j];
}
for (var k = 0; k < part2Arr.length; k++) {
if (sArr[i] == part2Arr[k]) tempArr[i] = part2Arr[k];
}
}
alert(tempArr);
if (compareArrays(tempArr, sArr)) return true;
else return false;
}
alert(isMerge('codewars', 'cdw', 'oears'));
Now, what was the problem?
for (var j = 0; j < part1Arr.length; j++) {
/* Here you assigned the index (tempArr[i] = j;) not the char */
if (sArr[i] == part1Arr[j]) tempArr[i] = part1Arr[j];
}
for (var k = 0; k < part2Arr.length; k++) {
/* Here you assigned the index (tempArr[i] = k;) not the char */
if (sArr[i] == part2Arr[k]) tempArr[i] = part2Arr[k];
}
Hope i could help you ;)
Simple merge logic:
function isMerge(s, part1, part2) {
var sArr = s.split('');
var part1Arr = part1.split('');
var part2Arr = part2.split('');
var j = 0;
var k = 0;
for (var i = 0; i < sArr.length; i++) {
if ((j < part1Arr.length) && (sArr[i] == part1Arr[j]))
j++
else if ((k < part2Arr.length) && (sArr[i] == part2Arr[k]))
k++
else
break
}
return (j == part1Arr.length && k == part2Arr.length && (j + k) == sArr.length);
}
console.log(isMerge('abcd', 'ac', 'bd'));
console.log(isMerge('abcd', 'acd', 'b'));
console.log(isMerge('abcd', 'ac', 'b'));
console.log(isMerge('abcd', 'ac', 'db'));
console.log(isMerge('abcd', 'c', 'b'));
console.log(isMerge('a', '', 'a'));
console.log(isMerge('', '', ''));
console.log(isMerge('', 'a', 'b'));
console.log(isMerge('ab', '', ''));

Multiple array intersection in 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);

how to using recursive function correctly in javascript?

I make a function used to return string with string value like this: "not aritmatic". But when I recursive my function to controll another action, my recursive function not work. how to doing recursive correctly in javascript?
//call function ArithGeo
ArithGeo([2, 4, 6, 8, 12]);
//build function ArithGeo
function ArithGeo(arr) {
var copy_arr = arr;
var array_selisih = [];
for (i = 0; i <= arr.length - 1; i++) {
array_selisih[i] = arr[i + 1] - arr[i];
}
var j = 0;
var x = array_selisih[0];
if (arr.length % 2 == 1) {
for (j = 0; j <= array_selisih.length - 2; j++) {
//alert(array_selisih[x]+":"+array_selisih[j]);
if (array_selisih[x] != array_selisih[j]) {
return 'notaritmatic';
}
}
} else if (arr.length % 2 == 0) {
for (j = 0; j <= array_selisih.length - 3; j++) {
// alert(array_selisih[x]+":"+array_selisih[j]);
if (array_selisih[x] != array_selisih[j]) {
return 'notaritmatic';
}
}
}
return "aritmatik";
//my problem is here
if (ArithGeo(copy_arr) == "notaritmatic") {
//do something when return value is not aritmatic string
alert('not aritmatic ok');
}
}
I am sorry if my algorithm is long, I just try to sharpen my skill to solve problem with own idea. -_-
https://jsfiddle.net/fwdgmvyw/

array of arrays who's objects' indices grow progressively

Simplified Version
for...
ar = [
{"element":"a","index":0},
{"element":"b","index":1},
{"element":"e","index":4},
{"element":"d","index":3}
];
should return...
ans = [[
{"element":"a","index":0},
{"element":"b","index":1},
{"element":"e","index":4}],
[{"element":"a","index":0},
{"element":"b","index":1},
{"element":"d","index":3}]
];
It could return arrays of just {"element":"e","index":4} and just {"element":"d","index":3} since there is nothing behind it, but it's not necessary.
Original
I have this array of elements...
ar = [
{"element":"c","index":2},
{"element":"a","index":0},
{"element":"b","index":1},
{"element":"e","index":4},
{"element":"d","index":3}
];
I'd like to return an array of arrays which contain sequences where the "index"'s of each object grow progressively, and have the max number of objects for which obj1[index] < nextobj[index].
i.e. it should return..
[
[{"element":"c","index":2}, {"element":"e","index":4}],
[{"element":"c","index":2}, {"element":"d","index":3}],
[{"element":"a","index":0}, {"element":"b","index":1}, {"element":"d","index":3}],
[{"element":"a","index":0}, {"element":"b","index":1}, {"element":"e","index":4}]
[{"element":"d","index":3}],
[{"element":"e","index":4}]
]
I've tried using ar.reduce but am not that familiar with it and don't know if it's appropriate for this instance.
Not sure why these are not listed in your example
[{ element="a", index=0}, { element="e", index=4}]
[{ element="a", index=0}, { element="d", index=3}]
[{ element="b", index=1}, { element="e", index=4}]
[{ element="b", index=1}, { element="d", index=3}]
but here is what could produce something close
var ar = [
{"element":"c","index":2},
{"element":"a","index":0},
{"element":"b","index":1},
{"element":"e","index":4},
{"element":"d","index":3}
];
var results = [];
traverse([], 0);
function traverse(r, startIdx)
{
if (startIdx >= ar.length){
console.log(r);
return;
}
for (var i = startIdx; i < ar.length ; i++){
if ((startIdx == 0) || (r[r.length - 1].index) <= ar[i].index) {
rCopy = r.slice(0);
rCopy.push(ar[i]);
traverse(rCopy, i + 1);
}
else if (r.length > 0) {
console.log(r);
}
}
}
JSFiddle1, JSFiddle2
var ar = [
{"element":"c","index":2},
{"element":"a","index":0},
{"element":"b","index":1},
{"element":"e","index":4},
{"element":"d","index":3}
];
var results = [];
traverse([], 0);
collapse(results);
//console.log(results);
for (var i = results.length - 1; i >= 0; i--) {
console.log(results[i]);
}
function traverse(r, startIdx) {
if (startIdx >= ar.length) {
results.push(r);
return;
}
for (var i = startIdx; i < ar.length ; i++) {
if ((startIdx == 0) || (r[r.length - 1].index) <= ar[i].index) {
rCopy = r.slice(0);
rCopy.push(ar[i]);
traverse(rCopy, i + 1);
}
else if (r.length > 0) {
results.push(r);
}
}
}
function collapse() {
for (var i = results.length - 1; i >= 0; i--) {
for (var j = results.length - 1; j >= 0; j--) {
if ((i !== j) && (contains(results[i], results[j]))) {
results[i].remove = true;
}
}
}
for (var i = results.length - 1; i >= 0; i--) {
if (results[i].remove) {
results.splice(i, 1);
}
}
}
// Checks if set1 is contained within set2
function contains(set1, set2) {
for (var i = 0; i < set1.length; i++) {
var found = false;
for (var j = 0; j < set2.length; j++) {
if (set1[i].index === set2[j].index) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
JSFiddle3

Categories

Resources