Comparing an array to an array set in JavaScript - 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)

Related

Get an element from an array at an index a user specified

I want to build a function that takes two inputs:
an array of arrays
index number
and then returns an array inside the input array that it located at the input index.
The following is the code I got so far.
So, if a user calls the function with the following inputs, the expected result is [4,5,6] .
const input = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const index = 1;
function grab(input, index) {
var result = [];
return result = input[index];
console.log(result);
};
const input = [
[1,2,3],
[4,5,6],
[7,8,9]
];
const index = 1;
const result= grab(input, index);
console.log(result);
function grab(arr, index){
return [...input[index]]; // return copy of selected array
// to return not a copy -> return input[index];
};
function grab(input, index){
var result = [];
for(var i=0; i<input.length; i++){
result.push(input[index][i]);
}
return result;
};
You could learn more about slicing 2-D arrays in javascript from this source:
1

How to get item from multiple consecutive arrays

I am having a little difficuly coming up with a solution to my problem.
I am trying to get the item at an index of a collection of arrays. I cannot actually concatenate the arrays, they need to stay seperate.
Normally, to get the 3rd item from an array, you would do:
function getItemFromJustOneArray(index){
var my_array = [1,2,3,4,5,6];
return my_array[index];
}
getItemFromJustOneArray(2); // returns 3
However, I have a bunch of arrays (could be any amount of arrays) and these arrays cannot be merged into one.
function getItemFromMultipleArrays(index){
var array1 = [1,2];
var array2 = [3,4,5];
var array3 = [6];
// I cannot use concat (or similar) to merge the arrays,
// they need to stay seperate
// also, could be 3 arrays, but could also be 1, or 5...
// return 3;
}
getItemFromMultipleArrays(2); // SHOULD RETURN 3
I have tried a bunch of lines that loops over the array, but I cannot really get a working solution.
Does someone know an elegant solution to this problem?
Nest all the arrays in another array. Then loop over that array, decrementing index by each array's length until it's within the length of the current element. Then you can return the appropriate element of that nested array.
function getItemFromMultipleArrays(index) {
var array1 = [1, 2];
var array2 = [3, 4, 5];
var array3 = [6];
var all_arrays = [array1, array2, array3];
var i;
for (i = 0; i < all_arrays.length && index >= all_arrays[i].length; i++) {
index -= all_arrays[i].length;
}
if (i < all_arrays.length) {
return all_arrays[i][index];
}
}
console.log(getItemFromMultipleArrays(2)); // SHOULD RETURN 3
Why not spread the arrays to a new one and use the index for the value?
function getItemFromMultipleArrays(index) {
const
array1 = [1, 2],
array2 = [3, 4, 5],
array3 = [6];
return [...array1, ...array2, ...array3][index];
}
console.log(getItemFromMultipleArrays(2)); // 3
Another approach by using an offset for iterating arrays.
function getItemFromMultipleArrays(index) {
const
array1 = [1, 2],
array2 = [3, 4, 5],
array3 = [6],
temp = [array1, array2, array3];
let j = 0;
while (index >= temp[j].length) index -= temp[j++].length;
return temp[j][index];
}
console.log(getItemFromMultipleArrays(2)); // 3
console.log(getItemFromMultipleArrays(5)); // 6
this should do it, just copying all the arrays into a "big" one and accessing it (added a helping function)
// this function takes any amount of arrays and returns a new
// "concatted" array without affecting the original ones.
function connectArrays(...arrays) {
return [...arrays.flat()];
}
function getItemFromMultipleArrays(index) {
var array1 = [1,2];
var array2 = [3,4,5];
var array3 = [6];
var allArrays = connectArrays(array1, array2, array3);
return allArrays[index];
}
getItemFromMultipleArrays(2); // SHOULD RETURN 3

How filter simple multidimensional array with only numbers

I have a multidimensional array like this:
let arr = [ [1,2,3], [3,4,6], [4,5,7], [8,9,3]];
and I need to use only a filter function for filtering this array. I must filter the array and create a new array from the current inner arrays which contain the number 3:
let myArr = [ [1,2,3], [3,4,6], [4,5,7], [8,9,3]];
function getVal(value, arr){
for(let i in arr){
for(let j in arr[i]){
if(arr[i][j] == value){
return true;
}
}
}
}
let newArr = myArr.filter(getVal(3, myArr));
My code is not working. Actually, it's working, but I don`t see any result.
The expected result is like this:
newArr = [[1,2,3], [3,4,6], [8,9,3]];
All I have found are filter methods with objects.
You need a different style of the callback.
const contains = v => a => a.includes(v);
var array = [[1, 2, 3], [3, 4, 6], [4, 5, 7], [8, 9, 3]],
result = array.filter(contains(3));
console.log(result);
Assuming that it is 2 dimensional array. Use indexOf to check inside arrays:
myArr.filter((a)=> { return a.indexOf(3)>=0})
cont result = arr.filter(a => a.includes(3));

Return numbers which appear only once (JavaScript)

Say I have the array [1,2,3,5,2,1,4]. How do I get make JS return [3,4,5]?
I've looked at other questions here but they're all about delete the copies of a number which appears more than once, not both the original and the copies.
Thanks!
Use Array#filter method twice.
var data = [1, 2, 3, 5, 2, 1, 4];
// iterate over elements and filter
var res = data.filter(function(v) {
// get the count of the current element in array
// and filter based on the count
return data.filter(function(v1) {
// compare with current element
return v1 == v;
// check length
}).length == 1;
});
console.log(res);
Or another way using Array#indexOf and Array#lastIndexOf methods.
var data = [1, 2, 3, 5, 2, 1, 4];
// iterate over the array element and filter out
var res = data.filter(function(v) {
// filter out only elements where both last
// index and first index are the same.
return data.indexOf(v) == data.lastIndexOf(v);
});
console.log(res);
You can also use .slice().sort()
var x = [1,2,3,5,2,1,4];
var y = x.slice().sort(); // the value of Y is sorted value X
var newArr = []; // define new Array
for(var i = 0; i<y.length; i++){ // Loop through array y
if(y[i] != y[i+1]){ //check if value is single
newArr.push(y[i]); // then push it to new Array
}else{
i++; // else skip to next value which is same as y[i]
}
}
console.log(newArr);
If you check newArr it has value of:
[3, 4, 5]
var arr = [1,2,3,5,2,1,4]
var sorted_arr = arr.slice().sort(); // You can define the comparing function here.
var nonduplicates = [];
var duplicates=[];
for (var i = 0; i < arr.length; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
duplicates.push(sorted_arr[i]);
}else{
if(!duplicates.includes(sorted_arr[i])){
nonduplicates.push(sorted_arr[i]);
}
}
}
alert("Non duplicate elements >>"+ nonduplicates);
alert("Duplicate elements >>"+duplicates);
I think there could exists option with Map.
function unique(array) {
// code goes here
const myMap = new Map();
for (const el of array) {
// save elements of array that came only once in the same order
!myMap.has(el) ? myMap.set(el, 1) : myMap.delete(el);
}
return [...myMap.keys()];
}
const array = [1,2,3,5,2,1,4];
//[11, 23, 321, 300, 50, 23, 100,89,300];
console.log(unique(array));

Remove elements from array using javascript filter

I have two arrays and want to remove duplicates using filter function.
Here is my code:
arr1 = [1, 2, 3, 1, 2, 3];
arr2 = [2, 3];
result = [1, 1];
var result = arr1.filter(function(value, index) {
for (var i = 0; i <= arr2.length; i++) {
if (value !== arr2[i]) {
return value === arr2[i];
}
}
}
Thanks in advance! Any help would be great!
You can try to convert arguments into array and then check if the value from the initial array is in arguments array:
function destroyer(arr) {
// Converting arguments into array
var args = Array.prototype.slice.call(arguments);
arr = arr.filter(function (val) {
return args.includes(val)===false;
});
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3); // returns[1,1]
First of all, if its not a problem adding a library. I am using uniq from underscore.js.
uniq_.uniq(array, [isSorted], [iteratee]) Alias: unique
Produces a duplicate-free version of the array, using === to test object
equality. In particular only the first occurence of each value is
kept. If you know in advance that the array is sorted, passing true
for isSorted will run a much faster algorithm. If you want to compute
unique items based on a transformation, pass an iteratee function.
_.uniq([1, 2, 1, 4, 1, 3]);
=> [1, 2, 4, 3]
Other solution is using pure JS:
var newArray = [1, 2, 2, 3, 3, 4, 5, 6];
var unique = newArray.filter(function(itm, i, a) {
return i == newArray.indexOf(itm);
});
alert(unique);
But first you will need to combine your arrays in a new array:
var newArray = arr1.concat(arr2);
JS Fiddle
I hope this helped! :)
Here's one way without the filter function:
var arr1 = [1, 2, 3, 1, 2, 3];
var newArr = [];
for(var i = 0;i < arr1.length;i++){
if (newArr.indexOf(arr1[i]) === -1) {
newArr.push(arr1[i]);
}
}
Just use Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
with Array.prototype.indexOf()
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
var arr1 = [1, 2, 3, 1, 2, 3],
arr2 = [2, 3],
result = arr1.filter(function (a) {
return !~arr2.indexOf(a);
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
As in this JS Fiddle, using filter()
arr1 = [1, 2, 3, 1, 2, 3];
arr2 = [2, 3];
result = [1, 1];
var result = arr1.filter(myFunc);
function myFunc(value) {
for (var i = 0; i < arr2.length; ++i) {
// to remove every occurrence of the matched value
for (var j = arr1.length; j--;) {
if (arr1[j] === arr2[i]) {
// remove the element
arr1.splice(j, 1);
}
}
}
}
document.getElementById('result').innerHTML = arr1;
console.log(arr1);
// Output: [1,1]
<div id="result"></div>

Categories

Resources