Map 2 array into 1 array object - javascript

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

Related

Merge objects from two arrays of object based in the index

i searched a lot about this but i do not find anything that can enlight me about my issue:
I have this code:
let array1 = ["a", "b", 3, {
p1: 'hola'
}, "c", "d"],
array2 = [1, 2, {
p1: 'adios'
}],
result = [],
i, l = Math.min(array1.length, array2.length);
for (i = 0; i < l; i++) {
if (typeof array1[i] === 'object' && typeof array2[i] === 'object') {
result.push(array2[i], ...(JSON.stringify() === JSON.stringify() ?
[] :
[array1[i]]
));
} else {
result.push(array2[i], array1[i]);
}
}
result.push(...array1.slice(l), ...array2.slice(l));
console.log(result);
i have modified the code with the suggestions, right now the code does this:
we have two array;
array1 = ["a", "b", 3, {p1: 'hello'},"c", "d"]
array2 = [1, 2, {p1: 'hello'}]
the result right now is this based in the code:
result: [1, 'a', 2, 'b', {p1: 'hello'}, 3, {p1: 'hello'}, 'c', 'd']
this work fine because i dont want to omit objects that are in different index between the two array, the problem right now is that when the objects in the two array are in the same index this code;
array1 = ["a", "b", {p2: 'goodbye'},"c", "d"]
array2 = [1, 2, {p1: 'hello'}]
result : [1, 'a', 2, 'b', {p1: 'hello'}, 'c', 'd']
This is my issue right now, what i want is that when there are object in the same index on two array compare the properties of the objects and is the same skip the first array object and pass the second to the final array, but if the properties are not the same, combine the properties of the object in one, this is the ideal result that i want:
array1 = ["a", "b", {p2: 'goodbye'},"c", "d"]
array2 = [1, 2, {p1: 'hello'}]
result : [1, 'a', 2, 'b', {p1: 'hello', p2: 'goodbye'}, 'c', 'd']
I think this is what you're after.
let array1 = ['a', 'b', { p2: 'goodbye' }, 'c', 'd'];
let array2 = [1, 2, { p1: 'hello' }];
let result = [];
for (let i = 0; i < Math.max(array1.length, array2.length); i++) {
if (typeof array1[i] == 'object' && typeof array2[i] == 'object') {
result.push({ ...array2[i], ...array1[i] });
} else {
array2[i] && result.push(array2[i]);
array1[i] && result.push(array1[i]);
}
}
console.log(result);
You could compare the items and if same omit the second item.
let array1 = ["a", "b", {p1: 'hello world'},"c", "d"],
array2 = [1, 2, {p1: 'hello world'}],
result = [],
i, l = Math.min(array1.length, array2.length);
for (i = 0; i < l; i++) {
result.push(array2[i], ...(JSON.stringify() === JSON.stringify()
? []
: [array1[i]]
));
}
result.push(...array1.slice(l), ...array2.slice(l));
console.log(result);

Convert object with multiple arrays to array of objects

I stuggle a lot with data I get from an API:
This is the way the data gets returned, the amout of arrays differs.
const objData = {
arr1: [1,2,3],
arr2: [1,2,1],
arr3: [2,1,2],
arr4: ["a","b", "c"]
}
This is the way it SHOULD look
const desired = [
{a: 1, b: 1, c: 2, d: "a"},
{a: 2, b: 2, c: 1, d: "b"},
{a: 2, b: 1, c: 2, d: "c"}
]
This gives me the desired result, but it is not dymanic, since I have to provide the names of the arrays, and the amount of arrays in the object is not allowed to change.
const DataObj = []
for (let i = 0; i < objData.arr1.length; i++) {
const objX = {
a: objData.arr1[i],
b: objData.arr2[i],
c: objData.arr3[i],
d: objData.arr4[i],
}
DataObj.push(objX)
}
Can anybody help me to solve this? How can I make this independent from the names of the arrays and the amount of arrays in the dataset?
You could map the arrays with new objects.
const
objData = { arr1: [1, 2, 3], arr2: [1, 2, 3], arr3: [2, 1, 2], arr4: ["a", "b", "c"] },
keys = { arr1: 'a', arr2: 'b', arr3: 'c', arr4: 'd' },
result = Object
.entries(objData)
.reduce((r, [key, array]) => array.map((v, i) => ({ ...r[i], [keys[key]]: v })), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Non functional approach, use integers to get your letters
const objData = {
arr1: [1, 2, 3, 5],
arr2: [1, 2, 1, 4],
arr3: [2, 1, 2, 3],
arr4: ["a", "b", "c", "d"]
}
const len = Object.values(objData)[0].length;
let cnt = 97;
let newObj = {};
const list = [];
for (let i = 0; i < len; i++) {
for (let key in objData) {
newObj[String.fromCharCode(cnt)] = objData[key][i];
++cnt
}
list.push(newObj);
cnt = 97;
newObj = {};
}
console.log(list)

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)

How to join two 2D array 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)

Convert two arrays into an object

var foo = { "a": [1,2,3] }
var bar = { "b": [7,8,9] }
output should look like this
[ {a: 1, b: 7}, {a: 2, b: 8}, {a:3, b: 9}]
How can I do this using ramda or javascript functional programming ?
I have done this using for loop i = 0, is it possible using functional ramda programming
If both arrays are always the same length, you can do this using map.
function mergeArrays(arr1, arr2) {
return arr1.map(function(item, index) {
return {
a: arr1[index], //or simply, item
b: arr2[index]
};
});
}
var a = [1, 2, 3];
var b = [7, 8, 9];
var joined = mergeArrays(a, b);
document.getElementById('result').innerHTML = JSON.stringify(joined, null, 2);
<pre id="result">
</pre>
You can achieve this using R.transpose to convert an array of [[1,2,3], [7,8,9]] to [[1, 7], [2, 8], [3, 9]] and then map over it with R.zipObj.
const fn = R.compose(
R.map(R.zipObj(["a", "b"])),
R.transpose
)
const a = [1, 2, 3], b = [7, 8, 9]
const result = fn([a, b])
console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
If you would prefer to pass a and b as two arguments to fn rather than an array then you can swap R.transpose in the example above with R.unapply(R.transpose).
Assuming you want [{a:1,b:7},{a:2,b:8},{a:3,b:9}] it can be done pretty easily with map using the index to get the value in b:
var result = a.map((v, i) =>({ a: v, b: b[i] }));
i am having an array
const peopleObject = { "123": { id: 123, name: "dave", age: 23 },
"456": { id: 456, name: "chris", age: 23 }, "789": { id: 789, name:
"bob", age: 23 }, "101": { id: 101, name: "tom", age: 23 }, "102":
{ id: 102, name: "tim", age: 23 } }
for this particular i have created a code that convrts array to object i hope this is usefull for you
const arrayToObject = (array) =>
array.reduce((obj, item) => {
obj[item.id] = item
return obj
}, {})
const peopleObject = arrayToObject(peopleArray)
console.log(peopleObject[idToSelect])
Your expected output doesn't have a valid format. You should store the data in array. Like ,
var output = [];
var a = [1,2,3], b = [7,8,9];
for(var i=0; i< a.length; i++){
var temp = {};
temp['a'] = a[i];
temp['b'] = b[i];
output.push(temp);
}
You cannot store the result in an object the way you want. Objects are key-value pairs. But what you expect is only the values without keys which is not possible!
create function form ramda's addIndex and map
const data = { keys: ['a', 'b', 'c'], values: ['11', '22', '33'] }
const mapIndexed = R.addIndex(R.map)
const result = mapIndexed((item, i) => {
return { [item]: data.values[i] }
}, data.keys)
You will get an array of objects

Categories