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

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

Related

How to get a reduced array? My array is not getting returned

I am trying to get a reduced array.
My output is supposed to be [1,5,4] but it gives me an empty array.
let arr=[1,[2,3],4]
let newarr=[]
let myarr=()=>{
for(i=0;i<3;i++){
array=arr[i].reduce
newarr.push(array)
return newarr
}
}
You need to pass a function to your array.reduce,also you have to actually call your function,like so ( console.log calls it ):
const arr = [1, [2, 3], 4];
const myArr = (arr) => {
let newArray = [];
arr.forEach((arrayItem) => {
//we iterate every item in given array
if (Array.isArray(arrayItem)) {
//we check if item is actually an array to reduce
newArray.push(
arrayItem.reduce(function (previous, current) {
return previous + current;
})
); //if its an array then reduce it down to a single value using a reducer function and push it in new array
} else {
newArray.push(arrayItem); //otherwise just push it in new array as is
}
});
return newArray;
};
console.log( myArr(arr) );
there are always shorter and prettier ways to do the same,above solution is as readable as possible to understand it,an one-liner would be :
const arr = [1, [2, 3], 4]
const newArr = arr.map(i=>Array.isArray(i)?i.reduce((a,b)=>a+b):i)
console.log(newArr)
Array#reduce is an array method and it needs a function to be passed to it. Also you have defined a function but you do not invoke it.
Try the following:
let arr = [1, [2, 3], 4];
let newarr = [];
((array) => {
for(let i=0; i < array.length; i++) {
const el = array[i];
const topush = Array.isArray(el) ? el.reduce((total, curr) => total + curr, 0) : el;
newarr.push(topush)
}
})( arr );
console.log( newarr );
Alternatively, you can use Array#map and Array#reduce methods as follows. In both cases the trick is to identify the array so as to apply reduce to it:
const arr = [1, [2, 3], 4, [4, 5, 7]];
const newarr = arr.map(el =>
Array.isArray(el) ? el.reduce((sum,cur) => sum + cur,0) : el
);
console.log( newarr );

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));

how to iterate array of array in javascript to get common item ?

/*1 2 3
2 1 3
2 3 1 */
var arr = [
[1,2,3],
[2,1,3],
[2,3,1]
]
function commonElementInColumn(arr){
var a = arr[0],
b=false,
commItem =[];
for(var i=0 ; i<a.length ;i ++){
var item = a[i];
for(j=1; j< arr.length ; j++){
if(arr[j].indexOf(item) !==-1){
b =true
}else {
b= false
}
}
if(b){
commItem.push(item)
}
}
return commItem
}
console.log(commonElementInColumn(arr))
I am trying to find common column item in matrix .I tried like this. But not getting expected output .I am getting [1,2,3] but
can we add any logic which find common element in columns
Expected output is [1]
Let take I have m x n matrix .I want to find common element which is present in all coloum.
See input
/*1 2 3
2 1 3
2 3 1 */
1 is present in all three column.
2 is present only first and second not in third
3 is present on second and third but not in first
Try following
var arr = [
[1,2,3], [2,1,3], [2,3,1]
];
// Create the map of items with value to be an array of indexes
var map = {};
var result = [];
// iterate over the array
arr.forEach(function(subArray){
subArray.forEach(function(item, index){
map[item] = map[item] ? map[item] : [];
// if the map has the item and the index already exists in the array, skip
if(!map[item].includes(index)) {
map[item].push(index);
}
// if the length is same as the array item length (assuming same for all subArray's) then it means all indexes have been covered
if(map[item].length === arr[0].length) {
result.push(item);
}
});
});
console.log(result);
A slightly different approach with a Map for the values and a Set for each value for collecting the indices. Later check the size of the sets and take the keys of the map as result arrray.
function commonCol(array) {
var map = new Map;
array.forEach(a => a.forEach((v, i) => {
if (!map.has(v)) {
map.set(v, new Set);
}
map.get(v).add(i);
}));
return Array
.from(map.entries())
.filter(({ 1: v }) => v.size === array[0].length)
.map(([k]) => k);
}
var array = [[1, 2, 3], [2, 1, 3], [2, 3, 1]];
console.log(commonCol(array));
Take a look at that:
var arr = [
[1,2,3],
[2,1,3],
[2,3,1]
]
// Creates another array from arr organized by column
var byColumn = arr.reduce((accumulator, item) => {
item.forEach((element, index) => {
if(!accumulator[index]) accumulator[index] = [];
accumulator[index].push(element);
});
return accumulator;
}, [])
// Gets the first array of arr to iterate
var firstArray = arr[0];
// Gets an array of elements that appears in all columns
var filteredNumbers = firstArray.filter(element => {
return byColumn.every(item => item.includes(element));
});
console.log(filteredNumbers); // [1]
Use Array#filter() on first subarray since it must contain any common values.
Within that filter use a Set to pass all indices for each number to. Since a Set must have unique values you can then check it's size and if it matches subarray length then all indices are unique
var arr = [
[1, 2, 3],
[2, 1, 3],
[2, 3, 1]
]
function commonElementInColumn(arr) {
// return filtered results from first subarray since it has to contain any common values `
return arr[0].filter((num) => {
// get all indices for this number as array
let indices = arr.map(subArr => subArr.indexOf(num));
//create a set from this array which will void duplicates
let uniqueIndices = new Set(indices);
// if size of set is same as subarray length then all indices for this number are unique
return uniqueIndices.size === arr[0].length;
});
}
console.log(commonElementInColumn(arr))

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)

Categories

Resources