compare single dimensional Array with Multidimensional array in javascript - javascript

I am using javascript to compare a single array and a multidimensional array.
Here i want to compare those 2 array and the matched value should be shown.
arr[1,2,3] value to be searched in multidimensional array " md2 ".
This is my Code :: i have taken an single array and other as multidimensional array
var arr = [1,2,3];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];
for(var j=0; j<md2.length ; j++){
if(arr == md2[j]){
console.log(arr + " ... " + md2[j]);
}
}
Required O/P :- [1,2,3] should match and should be displayed in the console

You can use .find() and .every() methods to find array inside multi-dimensional array:
var arr1 = [1,2,3];
var arr2 = [1,2,5];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];
var searchAndPrint = (a1, a2) => {
let arr = a1.find(a => a.every((v, i) => v === a2[i]));
if(arr)
console.log(arr);
else
console.log("No Results");
};
searchAndPrint(md2, arr1);
searchAndPrint(md2, arr2);

You can't compare arrays in js. If you wanna compare simple arrays you can convert them to string to compare. This method is not applicable to array containing objects.
var arr = [1,2,3];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];
for(var j=0; j<md2.length ; j++){
if(arr.toString() === md2[j].toString()){
console.log(arr + " ... " + md2[j]);
}
}

You can use JSON.stringify to compare the arrays.
var arr = [1,2,3];
var md2 = [[23,8,2],[1,5,8],[1,2,3],[8,5,2]];
for(var j=0; j<md2.length ; j++){
if(JSON.stringify(arr) === JSON.stringify(md2[j])){
console.log(arr + " ... " + md2[j]);
}
}

For checking, you need to check the length and the items directly, because you have no same object reference.
var arr = [1, 2, 3],
md2 = [[23, 8, 2], [1, 5, 8], [1, 2, 3], [8, 5, 2]];
console.log(md2.some(a => arr.length === a.length && a.every((v, i) => v === arr[i])));

Related

How do you merge the item values from 2 separate arrays in javascript?

I'm not looking to push the values from one array into another, or concatenate them but simply sum the item values from each - either into a new array, or alternatively amending either arrayOne or arrayTwo with the values from the other e.g.
var arrayOne = [1,2,3,4,5]
var arrayTwo = [2,4,6,8,10]
// loop / function..
var newArray = [3,6,9,12,15]
OR arrayOne = [3,6,9,12,15]
I thought this would be straightforward but this requires 2 loops running at the same time?
Thanks for your help!
var arrayOne = [1,2,3,4,5];
var arrayTwo = [2,4,6,8,10];
var newArray = [];
newArray = arr1.map((item,index)=>{
return item + arr2[index]
});
You could collect all wanted array for adding values at the same index in an array and reduce the arrays.
This works with an arbitrary count of arrays.
var array1 = [1, 2, 3, 4, 5],
array2 = [2, 4, 6, 8, 10],
result = [array1, array2].reduce(
(a, b) => (b.forEach((v, i) => a[i] = (a[i] || 0) + v), a)
);
console.log(result);
You can use Array's map():
var arrayOne = [1,2,3,4,5];
var arrayTwo = [2,4,6,8,10];
var newArray = arrayOne.map( (item, i) => item += arrayTwo[i] );
console.log(newArray);

How do I find the number of common numbers occurring in 2nd array?

commonCount(ar1, ar2)
if arr1 = [1,1,2,3,3] and arr2 = [1,4,3,1,1], the answer is 3
My thought process:
initialize accumulator
iterate through arr1
if arr1[i] is in the arr2, add 1 to the accumulator
remove the arr1[i] from arr2 (because don't want to have duplicate if the number already exist)
return accumulator
1) How do I check if arr1[i] is in the arr2?
2) How do I remove arr1[i] from arr2?
console.log([1,2,3,4,5].filter((n) => [1,1,2,10,11].includes(n)))
This is the code to calculate the intersection.
to filter them out you will do this
console.log([1,1,2,10,11].filter((n) => ![1,2,3,4,5].includes(n)))
To remove an element x from an array arr we can do this
var array = [1,2,3];
var index = array.indexOf(3);
if( index >= 0)
array.splice(index,1);
Removing an element also answers your question on how to check if the elements exist in the array.
try with arr2 .filter(val => !arr1.includes(val)); to remove duplicate value from second array
var arr1 = [1, 1, 2, 3, 3];
var arr2 = [1, 4, 3, 1, 1];
arr2 = arr2 .filter(val => !arr1.includes(val));
console.log(arr1);
console.log(arr2);
You can store all unique values along with its frequency in an object using array#reduce and then filter result by looking into unique object using array#filter and decrementing the frequency once you find the same value. After that simply return length.
const arr1 = [1,1,2,3,3],
arr2 = [1,4,3,1,1];
var commonCount = (ar1, ar2) => {
const uniques = ar1.reduce((res, v) => {
res[v] = (res[v] || 0) + 1;
return res;
},{});
const common = arr2.filter(v => uniques[v] > 0 && uniques[v]--);
return common.length;
}
console.log(commonCount(arr1,arr2));

Comparing an array to an array set in JavaScript

I want to compare an array with an array set.
For example,
array 1 = [[1,2,3],[1,4,5]];
array 2 = [1,3,6,5,4];
Since the elements 1,4,5 in array 2 match with a set in array 1 it should return true.
use loop and loop. get all child array in array1, and check each child array include in array2.
function check(){
var array1 = [[1,2,3],[1,4,5]];
var array2 = [1,3,6,5,4];
for(let arr of array1){
let flag=true;
for(let child of arr){
if(array2.indexOf(child) < 0){
flag = false;
break; // if one element not in array2, enter next loop.
}
}
if(flag) return flag; // if got one child array elements all in array2, stop loop.
}
}
Iterate over your array and check if the value exists in the other array.
var sets = [
[1, 2, 3],
[1, 4, 5]
],
valid = [1, 3, 6, 5, 4];
var processed = sets.map(set => set.every(val => valid.includes(val)));
console.log( processed);
There are ways to make this more efficient, but try this for starters.
Here's an example how you can check if any are true:
// Check if any are true
var any = processed.some(v=>v);
console.log( any );
You can iterate over array1 and use every() on each number group and as a condition for it use includes() with the second array for a relatively short syntax:
var array1 = [
[1, 2, 3],
[1, 4, 5]
];
var array2 = [1, 3, 6, 5, 4];
var results = [];
array1.forEach(function(item, index, array) {
if (item.every(x => array2.includes(x))) {
results.push(item)
}
});
console.log(results)
Edited : I'm pushing the results that return true to an empty array ...
Flatten the first array (unpack the nested arrays). Then do an intersection of the flattened array and the second array. Map through the first array, and for each each array do an intersection against the second array. Then filter out all arrays that are empty. If the resulting array contains something, then something matched.
const hasMatch = Boolean(array1.map(a => intersect(a, array2)).filter(i => i.length).length)
var array1 = [
[1, 2, 3],
[1, 4, 5]
];
var array2 = [1, 3, 6, 5, 4];
var isMatch = doesNestedArrayMatchArray(array1, array2);
function doesNestedArrayMatchArray(nestedArray, bigArray) {
var atLeastOneMatch = false;
for (var i = 0; i < nestedArray.length; i++) {
var innerMatch = true;
//go through each array of array1
for (var j = 0; j < nestedArray[i].length; j++) {
if (bigArray.indexOf(nestedArray[i][j]) == -1){
innerMatch = false;
break;
}
}
if (innerMatch) atLeastOneMatch = true;
}
return atLeastOneMatch;
}
console.log(isMatch)

JavaScript: Convert [a,b,c] into [a][b][c]

I have arrays like [a], [a,b], [a,b,c] and so on.
How can I convert them into [a], [a][b], [a][b][c] and so on?
Example:
var arr = [1,2,3,4];
arr = do(arr); // arr = arr[1][2][3][4]
You could map it with Array#map.That returns an array with the processed values.
ES6
console.log([1, 2, 3, 4].map(a => [a]));
ES5
console.log([1, 2, 3, 4].map(function (a) {
return [a];
}));
While the question is a bit unclear, and I think the OP needs possibly a string in the wanted form, then this would do it.
console.log([1, 2, 3, 4].reduce(function (r, a) {
return r + '[' + a + ']';
}, 'arr'));
Functional:
use .map like this
[1,2,3,4].map(i => [i])
Iterative:
var list = [1, 2, 3, 4], result = [];
for (var i=0; i<list.length; i++) {
result.push([list[i]]);
}
If I understand you correctly, you are converting single dimension array to multi dimensional array.
To do so,
var inputArray = [1,2,3,4];
var outputArray = [];
for(var i=0;i<inputArray.length;i++)
{
outputArray.push([inputArray[i]])
}
function map(arr){
var aux = [];
for(var i=0; i<arr.length;++i){
var aux2 = [];
aux2.push(arr[i]);
aux.push(aux2);
}
return aux;
}

Checking whether certain item is in certain array using javascript

I have 10 different arrays. Each array has different numbers.
array1 = [1,2,3,4,5]
array2 = [6,7,8,9,10]
...
array 10 = [51,52,53,54]
let's say I pass in 7. Then I want to know which array it is from and want to return array number. So in this case it is going to be 2.
Should I write a switch statement for each array? Appreciate it in javascript.
try:
var arrays = [array1, array2, ..., array10];
for(var i=0; i<arrays.length; ++i) {
if (arrays[i].indexOf(value) != -1) {
console.log('found in array' + (i+1));
}
}
You cannot directly retrieve the name of array.The reason is this variable is only storing a reference to the object.
Instead you can have a key inside the same array which represent its name. Then indexOf can be used to find the array which contain the number , & if it is so, then get the array name
var array1 = [1,2,3,4,5];
array1.name ="array1";
var array2 = [6,7,8,9,10];
array2.name ="array2";
var array10 = [51,52,53,54]
array10.name ="array10";
var parArray = [array1,array2,array10]
function _getArrayName(number){
for(var o=0;o<parArray.length;o++){
var _tem = parArray[o];
if(parArray[o].indexOf(number) !==-1){
console.log(parArray[o].name);
}
}
}
_getArrayName(6) //prints array2
jsfiddle
One fast method should be using hash tables or as i would like to call LUT. Accordingly this job boils down to a single liner as follows;
var arrs = {
arr1 : [1,2,3,4,5],
arr2 : [6,7,8,9,10],
arr3 : [12,14,16,17],
arr4 : [21,23,24,25,27,20],
arr5 : [31,34,35,39],
arr6 : [45,46,44],
arr7 : [58,59],
arr8 : [66,67,69,61],
arr9 : [72,73,75,79,71],
arr0 : [81,85,98,99,90,80]
},
lut = Object.keys(arrs).reduce((p,c) => {arrs[c].forEach(n => p[n]=c); return p},{}),
findar = n => lut[n];
document.write("<pre>" + findar(12) + "</pre>");
One way to do this is have the arrays in an object and iterate over the keys/values. This method doesn't presume the arrays (and therefore their names) are in sequential order.
Note: this will always return a the first match from the function and terminate the search.
var obj = {
array1: [1, 2, 3, 4, 5],
array2: [6, 7, 8, 9, 10],
array3: [51, 52, 53, 54],
array4: [51, 52, 53, 54, 7]
}
function finder(obj, test) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (obj[key].indexOf(test) > -1) {
return key.match(/\d+/)[0];
}
}
return false;
}
finder(obj, 7); // '2'
DEMO
If you want to find all instances of a value in all arrays the function needs to be altered slightly.
function finder(obj, test) {
var keys = Object.keys(obj);
var out = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (obj[key].indexOf(test) > -1) {
out.push(key.match(/\d+/)[0]);
}
}
return out;
}
finder(obj, 7); // ['2', '4']
DEMO

Categories

Resources