How to join two 2D array JavaScript - javascript

I have two 2D array and what to merge row VS row.
arr1 = [[a,b,c],[d,e,f],[g,h,i]]
arr2 = [[1,2,3],[4,5,6],[7,8,9]]
I want to have output like this
arr2 = [[a,b,c,1,2,3],[d,e,f,4,5,6],[g,h,i,7,8,9]]
How do I do this with map method?

const arr1 = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
];
const arr2 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const result = arr1.map((arr1Item, i) => [...arr1Item, ...arr2[i]]);
console.log(result);

You can use concat with map:
var arr1 = [['a','b','c'],['d','e','f'],['g','h','i']];
var arr2 = [[1,2,3],[4,5,6],[7,8,9]];
var result = arr1.map((k,i)=>k.concat(arr2[i]));
console.log(result);

you could use map, map and push like so...
const foo = [
['a','b','c'],
['d','e','f'],
['g','h','i']
]
const bar = [
[1,2,3],
[4,5,6],
[7,8,9]
]
foo.map((el, i) => {
el.map((e) => {
bar[i].push(e)
})
})
console.log(bar)

Related

More efficient, but readable alternative for this block of JavaScript code

Let's say I got 3 arrays, of which one is based on the other array, but I need to combine them into one.. I'm using forEach loops here to push items to the array but I feel like that's inefficient.
const arr1 = [1, 2, 3];
const arr2 = ["a", "b"];
const arr3 = ["foo", "bar", "baz"];
const obj = {
"1_a": [1, 2],
"1_b": [1, 2, 3],
"2_a": [1],
"2_b": [1, 2],
"3_a": [],
"3_b": [1, 2, 3]
};
// push all the items to the temporary array - with forEach loops,
// I feel like this logic can be made more readable and efficient
let tempArr = [];
arr1.forEach(i =>
arr2.forEach(j =>
tempArr.push(`${i}_${j}`)
)
);
arr3.forEach(i => tempArr.push(i));
// loop over the temporary array to get the final result (logged below)
const arr = tempArr.map(key => {
if (obj[key] !== undefined && obj[key].length > 1) return `update_${key}`;
else return key;
});
// result
console.log(arr); // [ "update_1_a", "update_1_b", "2_a", "update_2_b", "3_a", "update_3_b" ]
I feel like I'm doing something wrong here with all the forEach pushes, I feel like there should be something like a nested map function..? Please help me out here..
I would like the following to happen:
The values of arr2, are based on the loop of arr1 (see example), these get combined with an underscore, pseudo: arr1Item_arr2Item, and this item gets pushed to the array.
The values of arr3, just get looped and pushed
The merged array gets looped, and in case the value of that item is in the object, and the array of that key is longer than 1, return update_<arrItem>, else just return <arrItem>
Not sure if it's any better, but it is a reduce and a map:
const arr1 = [1, 2, 3];
const arr2 = ["a", "b"];
const arr3 = ["foo", "bar", "baz"];
const obj = {
"1_a": [1, 2],
"1_b": [1, 2, 3],
"2_a": [1],
"2_b": [1, 2],
"3_a": [],
"3_b": [1, 2, 3],
};
const result = arr1.reduce(
(a, c) =>
(a.concat(
arr2.map((y) => {
const key = `${c}_${y}`;
return obj[key] !== undefined && obj[key].length > 1
? `update_${key}`
: key;
})
)),
arr3
);
console.log(result);
you can try:
const arr1 = [1, 2, 3];
const arr2 = ['a', 'b'];
const obj = {
'1_a': [1, 2],
'1_b': [1, 2, 3],
'2_a': [1],
'2_b': [1, 2],
'3_a': [],
'3_b': [1, 2, 3]
};
const result = arr1.reduce((acc, a1) =>
[...acc, ...arr2.map(a2 => {
const keyCombined = `${a1}_${a2}`;
return obj[keyCombined].length > 1
? `update_${keyCombined}`
: `${keyCombined}`;
})], []);
console.log(result);
Another approach using flatMap:
const arr1 = [1, 2, 3];
const arr2 = ["a", "b"];
const arr3 = ["foo", "bar", "baz"];
const obj = {
"1_a": [1, 2],
"1_b": [1, 2, 3],
"2_a": [1],
"2_b": [1, 2],
"3_a": [],
"3_b": [1, 2, 3]
};
const result = [
...arr3,
...arr1
.flatMap(a => arr2
.map(b => {
const key = `${a}_${b}`;
return obj[key].length > 1
? `update_${key}`
: key;
}))
]
console.log(result)

JavaScript How to replace first element of an array with each element of another array

I have two arrays and I need to replace the first element of the first array with each elements of the second array:
let firstArray = [
[1, 'a', 'hello'],
[2, 'b', 'world'],
[3, 'c', 'other'],
...
];
let secondArray = [1, 3, 7, ...];
// Result:
// [
// [1, 'a', 'hello'],
// [3, 'b', 'world'],
// [7, 'c', 'other'],
// ...
// ]
I tried doing something like this:
firstArray.map(f => {
secondArray.forEach(s => {
f.splice(0, 1, s);
})
})
But this replace the first element only with the last element of second array
Use .map to transform an array into another:
const firstArray = [
[1, 'a', 'hello'],
[2, 'b', 'world'],
[3, 'c', 'other'],
];
const secondArray = [1, 3, 7];
const transformed = firstArray.map(([, ...rest], i) => [secondArray[i], ...rest]);
console.log(transformed);
Another option:
const firstArray = [
[1, 'a', 'hello'],
[2, 'b', 'world'],
[3, 'c', 'other'],
];
const secondArray = [1, 3, 7];
const transformed = firstArray.map((item, i) => [secondArray[i]].concat(item.slice(1)));
console.log(transformed);
You could assign the array to a new array and take the new value to a specified index.
const
firstArray = [[1, 'a', 'hello'], [2, 'b', 'world'], [3, 'c', 'other']],
secondArray = [1, 3, 7],
result = firstArray.map((a, i) => Object.assign([], a, { 0: secondArray[i] }));
console.log(result);

How to put distribute array into arrays of arrays?

I'm new to node js/express. I'm having the problem cause I need to insert bulk in MySQL. I use body-parser, but to simplify my code this is the analogy.
I have two objects from req.body:
Numbers = { 1, 2, 3 }
Letters = { a, b, c }
Then, I need it to be like this,
Object = [ { '1', 'a' }, { '2', 'b' }, { '3', 'c' } ]
What can I use to do this?
const Numbers = [1, 2, 3]
const Letters = ['a', 'b', 'c']
const result = []
Numbers.forEach((el, i) => {
result.push({[el]: Letters[i]})
})
console.log(result)
or
const Numbers = [1, 2, 3]
const Letters = ['a', 'b', 'c']
const result = Numbers.map((el, i) => ({[el]: Letters[i]}))
console.log(result)

Map 2 array into 1 array object

I have 2 separate array but both of them have same length. How to merge them together into an array object so that it's easy to populate later?
for example
[1,2,3,4,5]
['a','b','c','d','e']
I expect I can have something like
[{'index':1,'value':'a'},{'index':2,'value':'b'}]
I've tried
$.each(a, function(i,x){
$.each(b, function(i,z){
c['index'] = x;
c['value'] = z;
});
});
But I got only [{'index':'1','value':'a'}]
You can use map() for iterate and generate the new array
var arr1 = [1, 2, 3, 4, 5],
arr2 = ['a', 'b', 'c', 'd', 'e'];
var res = arr1.map(function(v, i) {
return {
index: v,
value: arr2[i]
};
})
document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');
With ES6 you can do it with arrow function like below:
const arr1 = [1, 2, 3, 4, 5];
const arr2 = ["a", "b", "c", "d", "e"];
const output = arr1.map((el, i) => ({ index: el, value: arr2[i] }));
console.log(output);

a function to search array

How can I search for an element within a nested array. Following is what the array looks like
arr = [
["choice1", ['a', [2, 4]], ['b', [1, 3, 4]], ['c', [3, 4]]],
["choice2", ['b', [1, 4]], ['c', [1, 3]]],
["choice3", ['b', [1, 2, 4]], ['c', [1, 2, 3, 4]]]
]
if 'a' is equal to '2' then the following function has to return "choice1" and "choice3" in the 'result':
function arraySearch(arr, a) {
var result = [];
for(var i = 0; i < arr.length; i++) {
// compare each arr[i] with 'a' for the very first occurrence, and move the next array
if(arr[i].search(a)){
result.concat(arr[0]);
}
}
return result;
}
Please help. Many thanks in advance.
something like
arr = [
["choice1", ['a', [2, 4]], ['b', [1, 3, 4]], ['c', [3, 4]]],
["choice2", ['b', [1, 4]], ['c', [1, 3]]],
["choice3", ['b', [1, 2, 4]], ['c', [1, 2, 3, 4]]]
];
find = function(arr, a) {
var found = [];
var foundCurrent;
// for each 'choice'
for (var choice = 0; choice < arr.length; choice++) {
foundCurrent = false;
// look at each entry in the array that is arr[current][1]
for (var entry = 1; entry < arr[choice].length; entry++) {
// search these for the value
if (arr[choice][entry][1].indexOf(a) != -1) {
if (!foundCurrent) {
found[found.length] = arr[choice][0];
}
foundCurrent = true;
}
}
}
return found;
};
find(arr, 2);
>> [choice1, choice3]
It's not clear to me exactly what you need.
If you want to know whether an array contains an element, use Array.indexOf.

Categories