Iterate an array of arrays for a match from another array - javascript

I have an array of arrays, and I would like to iterate this array with the values of another array looking for a match.
let arr1 = [[1,3,5],[2,4,7],[1,5,9]] // [false, false, true]
let arr2 = [1,2,4,5,9] // arr2 contains all values of arr1[2]. return true.
I need it to return truthy falsey if all values in an arr1[i] are present in arr2
for (let i = 0; i < arr1.length; i++) {
if (arr2.every(arr1[i])) {
return true
}
}

You can use .map() with .every()
let arr1 = [[1,3,5],[2,4,7],[1,5,9]];
let arr2 = [1,2,4,5,9];
let result = arr1.map(x => x.every(y => arr2.includes(y)));
console.log(result);
or .filter() if you just want to get matching results:
let arr1 = [[1,3,5],[2,4,7],[1,5,9]];
let arr2 = [1,2,4,5,9];
let result = arr1.filter(x => x.every(y => arr2.includes(y)));
console.log(result);

You could use Array#some for a single boolean value by using Array#every for each inner array and check array2 with Array#includes.
var array1 = [[1, 3, 5], [2, 4, 7], [1, 5, 9]],
array2 = [1, 2, 4, 5, 9],
result = array1.some(a => a.every(v => array2.includes(v)));
console.log(result);
Using a Set.
var array1 = [[1, 3, 5], [2, 4, 7], [1, 5, 9]],
array2 = [1, 2, 4, 5, 9],
result = array1.some((s => a => a.every(v => s.has(v)))(new Set(array2)));
console.log(result);

Related

Fill an array with consecutive numbers

I have an array that looks like this: [[3, Apple], [4, Banana], [7, Orange], [9, Pear]]
Now I'd like to add all missing numbers from 1 to 10 with empty entries where I have the fruit in the example, so that as result I'd have:
[
[1, ],
[2, ],
[3, Apple],
[4, Banana],
[5, ],
[6, ],
[7, Orange],
[8, ],
[9, Pear]
[10, ]
]
I'd share what I've tried so far, but I really am stuck at the beginning. Has anybody an idea how to accomplish that?
let result = []
let fruits = [[3, 'Apple'], [4, 'Banana'], [7, 'Orange'], [9, 'Pear']]
let fruitsObject = Object.fromEntries(fruits)
for (let i = 1; i<=10; i++){
result.push(fruitsObject[i] ? [i, fruitsObject[i]] : [i])
}
console.log(result)
You can start by creating an array with indexes only, and then iterate over your data to fill in the missing values from your input.
const data = [[3, "Apple"], [4, "Banana"], [7, "Orange"], [9, "Pear"]]
const result = data.reduce((result, [id, val]) => {
result[id - 1].push(val);
return result;
}, Array.from({length: 10}, (_, i)=> [i + 1]))
console.log(result);
Here 2nd argument of the reduce function is an array of length 10, filled with 1 element arrays, where element is an index + 1.
The first argument is a function called on every element of your input data, that modifies the 2nd argument.
A kind of over-engineering way. Don't be so hard on me.
const sourceArr = [[3, 'Apple'], [4, 'Banana'], [7, 'Orange'], [9, 'Pear']];
const sourceObj = Object.fromEntries(sourceArr);
const nullArr = [...Array(10).keys()].map(i => [i+1]);
const nullObj = Object.fromEntries(nullArr);
const unionObj = { ...nullObj, ...sourceObj };
const pairs = Object.entries(unionObj)
const result = pairs.map(pair => pair.filter(e => e));
console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

How can I insert each of an arrays elements every other element in another array? [duplicate]

This question already has answers here:
Merge two arrays with alternating values
(14 answers)
Merge Two Arrays so that the Values Alternate
(6 answers)
interleave mutliple arrays in javascript
(2 answers)
Closed 1 year ago.
I have two arrays.
let a = [1, 3, 5, 7]
let b = [2, 4, 6, 8]
I want the result:
a = [1, 2, 3, 4, 5, 6, 7, 8]
How can I insert each of array B's elements every other element in array A?
I have tried using splice in a for loop, but the length of array A changes so I cannot get it to work.
You can create a new array, loop through a and push the current item and the item in b at the same index:
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let res = []
a.forEach((e,i) => res.push(e, b[i]))
console.log(res)
Alternatively, you can use Array.map and Array.flat:
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let res = a.map((e,i) => [e, b[i]]).flat()
console.log(res)
If the arrays have the same length, then you can use flat map to avoid mutating the original array.
const a = [1, 3, 5, 7];
const b = [2, 4, 6, 8];
const res = b.flatMap((elem, index) => [a[index], elem]);
console.log(res);
You can try:
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8]
let newArray = [...a, ...b]
console.log(newArray) // [1, 3, 5, 7, 2, 4, 6, 8]
If you want to sort just
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8]
let newArray = [...a, ...b].sort((a, b) => a - b)
console.log(newArray) // [1, 2, 3, 4, 5, 6, 7, 8]
Create a new array and flatten it by doing the below.
let a = [1, 3, 5, 7]
let b = [2, 4, 6, 8]
console.log(a.map((e, i)=> [e, b[i]]).flat());
You could transpose the data and get a flat array.
const
transpose = (a, b) => b.map((v, i) => [...(a[i] || []), v]),
a = [1, 3, 5, 7],
b = [2, 4, 6, 8],
result = [a, b]
.reduce(transpose, [])
.flat();
console.log(result);
Don't splice, just create a new array and push them in on every other index.
Do a for loop, and on each loop do
newArrary.push(a[i]);
newArrary.push(b[i]);
You can use reduce
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let c = a.reduce((acc, x, i) => acc.concat([x, b[i]]), []);
console.log(c)
This works for arrays of any length, adapt the code based on the desired result for arrays that are not the same length.
Using forEach and pushing the current element and the relative element from the other array is an option
let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let c = [];
a.forEach((x, i) => {c.push(x, b[i])});
console.log(c);
More about forEach - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

interleave mutliple arrays in javascript

We have an Array of arrays, which we want to interleave into a single array:
i.e:
masterArray = [[1, 2, 3], ['c', 'd', 'e']] => [1, 'c', 2, 'd', 3, 'e'],
if arrays are not of equal length, pad it to the longest innerArray's length.
i.e
[1, 2, 3], [4, 5]) => [1, 4, 2, 5, 3, null]
I've satisfied this condition with the case of 2 arrays, however if the case is more than that. I struggle to form a strategy on dealing with more than 2.
[1, 2, 3], [4, 5, 6], [7, 8, 9] => [1, 4, 7, 2, 5, 8, 3, 6, 9]
function interleave(...masterArray) {
let rtnArray = [];
let longestArrayPosition = getLongestArray(masterArray);
let longestInnerArrayLength = masterArray[longestArrayPosition].length;
padAllArraysToSameLength(masterArray, longestInnerArrayLength); //pad uneven length arrays
masterArray[0].forEach((firstArrayNum, index) => {
const secondArrayNum = masterArray[1][index];
rtnArray.push(firstArrayNum);
rtnArray.push(secondArrayNum);
});
return rtnArray;
}
function getLongestArray(masterArray) {
return masterArray
.map(a=>a.length)
.indexOf(Math.max(...masterArray.map(a=>a.length)));
}
function padAllArraysToSameLength(masterArray, maxLength) {
return masterArray.forEach(arr => {
if (arr != maxLength) {
while(arr.length != maxLength) {
arr.push(null);
}
}
})
}
Use Array.from() to transpose the array of arrays (rows => columns and vice versa), and fill in the missing places with null. Flatten the tramsposed arrays of arrays with Array.flat():
const fn = arr => Array.from({
length: Math.max(...arr.map(o => o.length)), // find the maximum length
},
(_, i) => arr.map(r => r[i] ?? null) // create a new row from all items in same column or substitute with null
).flat() // flatten the results
const arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
const result = fn(arr)
console.log(result)
You can do this for any number of arrays with two nested forEach statements:
let arr1 = [[1,2,3],[4,5]]
let arr2 = [[1,2,3], [4,5,6], [7,8,9]]
let arr3 = [[1,2,3,4], [4,5,6], [7,8,9], [10,11,12]]
function interLeaveArrays(mainArr){
let maxLen = Math.max(...mainArr.map(arr => arr.length))
mainArr.forEach(arr => {
let lenDiff = maxLen - arr.length
for(let i=lenDiff; i>0; i--){
arr.push(null)
}
})
let newArr = []
mainArr.forEach((arr, idx1) => {
arr.forEach((el, idx2) => {
newArr[idx2 * mainArr.length + idx1] = el
})
})
return newArr
}
console.log(interLeaveArrays(arr1))
console.log(interLeaveArrays(arr2))
console.log(interLeaveArrays(arr3))

Assigning key's to array objects

I'm trying to solve this problem. Essentially, I have a array of keys, and an array of values within objects, and I want those values to have keys.
Below is my best attempt so far - usually use python so this is a bit confusing for me.
var numbers = [3, 4, 5,6]
var selection = [[1, 2, 3, 4], [6, 5, 4, 3], [2, 9, 4]]
var result = [];
for (arr in selection) {
numbers.forEach(function (k, i) {
result[k] = arr[i]
})
};
console.log(result);
The output I'm looking for is like this,
results = [{3:1,4:2,5:3,6:4}, {..},..]
Love some pointers to getting the right output.
Note. This is for google appscript! So can't use certain javascript functions (MAP I think doesn't work, unsure of reduce).
Cheers!
Use map on selection and Object.assign
var numbers = [3, 4, 5, 6];
var selection = [
[1, 2, 3, 4],
[6, 5, 4, 3],
[2, 9, 4]
];
var result = selection.map(arr =>
Object.assign({}, ...arr.map((x, i) => ({ [numbers[i]]: x })))
);
console.log(result);
Create a separate function which take keys and values as arguments and convert it into object using reduce(). Then apply map() on selections and make an object for each subarray using that function
var numbers = [3, 4, 5,6]
var selection = [[1, 2, 3, 4], [6, 5, 4, 3], [2, 9, 4]]
function makeObject(keys, values){
return keys.reduce((obj, key, i) => ({...obj, [key]: values[i]}),{});
}
const res = selection.map(x => makeObject(numbers, x));
console.log(res)
Create a new object from scratch for each number array:
const selection = [
[1, 2, 3, 4],
[6, 5, 4, 3],
[2, 9, 4],
];
function objMaker(numarr) {
const numbers = [3, 4, 5, 6];
numarr.forEach((num, i) => (this[numbers[i]] = num));
}
console.info(selection.map(numarr => new objMaker(numarr)));

Comparing 2 arrays of objects and removing the duplicates javascript

I'm trying to compare 2 array of objects together and remove the duplicates. For example...
var array1 = [0, 1, 2, 3, 4, 5, 6];
var array2 = [7, 8, 1, 2, 9, 10];
How can I check the array2 for any element of array1 and if true then remove that from array2 to eliminate the duplication.
The expected result: array 2 = [7, 8, 9, 10]
Any help would be appreciated, thanks
If the array include primitive types you can use indexOf and array#reduce
const array1 = [0, 1, 2, 3, 4, 5, 6]
const array2 = [7, 8, 1, 2, 9, 10]
var result = array2.filter((num) => {
return array1.indexOf(num) === -1;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
In case of an object, you can get the unique values in second array in comparison to first, please use array#reduce and array#some.
const person1 = [{"name":"a", "id":0},{"name":"A", "id":1},{"name":"B", "id":2},{"name":"C", "id":3},{"name":"D", "id":4},{"name":"E", "id":5},{"name":"F", "id":6}]
const person2 = [{"name":"G", "id":7},{"name":"H", "id":8},{"name":"A", "id":1},{"name":"B", "id":2},{"name":"I", "id":9}, {"name":"J", "id":10}]
var unique = person2.reduce((unique, o) => {
let isFound = person1.some((b) => {
return b.id === o.id;
});
if(!isFound)
unique.push(o);
return unique;
},[]);
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
just filter second array.
const array1 = [0, 1, 2, 3, 4, 5, 6];
const array2 = [7, 8, 1, 2, 9, 10];
const newArray = array2.filter(i => !array1.includes(i));
console.log(newArray);
You can use do this:
var array1 = [0, 1, 2, 3, 4, 5, 6];
var array2 = [7, 8, 1, 2, 9, 10];
/* run a filter function for every value in array2 and returned the final filtered array */
var array3 = array2.filter(function(currentValue, index, arr){
return (array1.indexOf(currentValue) === -1); /* this will check whether currentValue exists in aray1 or not. */
});
console.log(array3) /* filtered array */
This should deliver what you want. Or another way:
var array1 = [0, 1, 2, 3, 4, 5, 6];
var array2 = [7, 8, 1, 2, 9, 10];
var duplicateRemoved = [];
/* run a function for every value in array2 and collect the unique value in a new array */
array2.forEach(function(currentValue, index, arr){
if (array1.indexOf(currentValue) === -1) {
duplicateRemoved.push(currentValue);
}
});
console.log(duplicateRemoved)
This should work in your situation unless there are some other external factors associated with it.

Categories

Resources