How to use one array as keys for another array? - javascript

I have these two arrays and I want to output it like this:
{
"PT": "100",
"ES": "400",
"FR": "550",
"CH": "200",
"BR": "400",
"DE": "500",
}
How can I do that? Probably its simple but I can't figure out how to do this, also I searched on stackoverflow and I didn't find anything like this..
This is a project in React, I don't know if that matter.
Thanks.

It looks like those are what we call parallel arrays: The element at index n of one array relates to the element at index n of the other.
That being the case, you can use a simple for loop and brackets property notation:
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = array2[index];
}
Live Example:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = array2[index];
}
console.log(result);
You can also use map with Object.fromEntries to create the object, but it's more complicated (though shorter) and involves temporary array objects:
const result = Object.fromEntries(
array1.map((array1value, index) => [array1value, array2[index]])
);
Live Example:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = Object.fromEntries(
array1.map((array1value, index) => [array1value, array2[index]])
);
console.log(result);
Side note: In your output, you've shown the values 100, 200, etc. as strings, but they're numbers in your input. If you want them to be strings, just convert them as you go, like this:
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = String(array2[index]);
// −−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^−−−−−−−−−−−−−^
}
Live Example:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = String(array2[index]);
}
console.log(result);
You'll get people pointing you at reduce, but reduce is only useful when you're doing functional programming with predefined, reusable reducer functions. Otherwise, it's just an overcomplicated, error-prone loop where using an actual loop would be clearer and easier to get right.
In a comment you've asked:
What If I want it do be like this? [{ text: 'pt', value: 100, }, { text: 'es', value: 500, }] ?
To do that, you want to create an object for each entry in the array. You can create the array via map, and you can create an object using an object literal ({text: "PT", value: 100} and similar, but getting the values from the array):
const result = array1.map((text, index) => ({text: text, value: array2[index]}));
or using shorthand property notation for the text property:
const result = array1.map((text, index) => ({text, value: array2[index]}));
Live Example:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = array1.map((text, index) => ({text, value: array2[index]}));
console.log(result);
I've left those text values in upper case, but if you want to make them lower case in the objects, use .toLocaleLowerCase() on them:
const result = array1.map((text: text.toLocaleLowerCase(), index) => ({text, value: array2[index]}));

const arr1 = [100, 200, 300]
const arr2 = ["PT", "AT", "CT"]
const obj = {}
arr1.forEach((item, index) => {
obj[arr2[index]] = item
})
console.log(obj)

You can use .forEach to loop through one array and then populate the object.
const keys = ["PT", "ES", "FR", "CH", "BR", "DE"]
const values = ["100","400", "550", "200", "400", "500"]
const myObj = {}
keys.forEach((key,i) => myObj[key] = values[i]);
console.log(myObj);

a = ['a', 'b', 'c']
b= [1, 2, 3]
c = a.reduce((acc, item, index) => {
acc[item] = b[index];
return acc
}, {})
// {a: 1, b: 2, c: 3}

You can do this in a very simple loop:
const arr1 = ['key', 'key2', 'key3'];
const arr2 = ['val', 'val2', 'val3'];
const obj = {};
for (let i = 0; i < arr1.length; i++) {
obj[arr1[i]] = arr2[i];
}
console.log(obj);
This will result in an object like this:
{
key: 'val',
key2: 'val2',
key3: 'val3'
}

Related

How to create array of object from two different length of array javascript

How to create array of object from two different length of array
for example
arr1 = ["first","second","third","fourth","fifth","Sixth"]
arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]]
finalArray = [{
first:1,
second:2
third:3,
fourth:4,
fifth:5,
sixth:6
},{
first:7,
second:8
third:9,
fourth:10,
fifth:11,
sixth:12
}]
I tried this using map but getting every key value pair as whole object
example
[
{first: 1}
{second: 2}
{third: 3}
{fourth: 4}
]
With map() and reduce():
const arr1 = ["first", "second", "third", "fourth", "fifth", "Sixth"];
const arr2 = [["1", "2", "3", "4", "5", "6"],
["7", "8", "9", "10", "11", "12"],
["1", "2", "3", "4"]];
const res = arr2.map(v => v.reduce((a, v, i) => ({...a, [arr1[i]]: v}), {}));
console.log(res);
You can take advantage of Array.prototype.reduce to update the shape of the result array
let arr1 = ["first","second","third","fourth","fifth","Sixth"];
let arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]];
let result = arr2.reduce((accumulator, current) => {
let obj = arr1.reduce((acc, currentKey, index) => {
if(current.indexOf(index) && current[index] !== undefined ){
acc[[currentKey]] = current[index];
}
return acc;
}, {});
return accumulator.concat(obj);
}, []);
console.log(result);
without reduce() and covered edge case when the arr1 contains fewer elements as the element from arr2
const arr1 = ["first","second","third","fourth","fifth","Sixth"]
const arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]]
const res = arr2.map(values => {
const res = {}
for(const [index, value] of arr1.entries()){
if(values[index]) {
res[value] = values[index] // or parseInt(values[index])
} else {
break
}
}
return res
})
console.dir(res)

In array of objects turn object values into key/value pair

I am interested to use chartkick and so I need to convert JS object with the following format:
var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
To the following format:
var arrayOne = [{'01/01/2017': 200}, {'02/01/2017': 220},{'03/01/2017':250}]
Any help would be greatly appreciated.
Use Array.prototype.map():
const src = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}],
result = src.map(({date,value1}) => ({[date]: value1}))
console.log(result)
.as-console-wrapper{min-height:100%;}
You can try this
let sampleArray = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
let finalArray = sampleArray.map(data => ({[data.date]:data.value1}))
console.log(finalArray)
Output Will be
[{01/01/2017: 200},{02/01/2017: 220},{03/01/2017: 250}]
var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}];
var mappedArray = array.map(item => {
return {
[item.date]: item.value1
}
})
loop the array and map it to the new structure
Try this:
var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
let final_array = array.map(arr => {
return {[arr.date] : arr.value1};
})
console.log(final_array)
If you want to do it in a loop for each value1, value2, ...
var array = [{
date: '01/01/2017',
value1: 200,
value2: 300,
value3: 400
}, {
date: '02/01/2017',
value1: 220,
value2: 330,
value3: 430
}, {
date: '03/01/2017',
value1: 250,
value2: 330,
value3: 420
}]
const numberOfValues = 3;
for (let i = 1; i <= numberOfValues; i++) {
const mappedArray = array.map(x => {
const result = {};
result[x.date] = x["value" + i.toString()];
return result;
});
console.log(mappedArray);
}

How to calculate the sum of items in an array?

Suppose i have an array:
const items = [
{
"amount1": "100",
"amount2": "50",
"name": "ruud"
},
{
"amount1": "40",
"amount2": "60",
"name": "ted"
}
]
I want to get all amount1 and amount2 props totalled and result in:
[
{
"amount1": 140,
"amount2": 110
}
]
How can I do this?
Using Array.prototype.reduce() with Object.entries() and Array.prototype.forEach():
const items = [{amount1: 100, amount2: 50}, {amount1: 40, amount2: 60}];
const sums = items.reduce((acc, item) => {
Object.entries(item).forEach(([k, v]) => acc[k] = (acc[k] || 0) + v);
return acc;
}, {});
console.log(sums);
To filter out non-number properties (but keep quoted number strings, as per the updated question):
const items = [{amount1: '100', amount2: '50', name: 'Ruud'}, {amount1: '40', amount2: '60', name: 'Ted'}];
const sums = items.reduce((acc, item) => {
Object.entries(item)
.filter(([_, v]) => !isNaN(v))
.forEach(([k, v]) => acc[k] = (acc[k] || 0) + Number(v));
return acc;
}, {});
console.log(sums);
const items = [{amount1: 100, amount2: 50}, {amount1: 40, amount2: 60}];
function sum(data){
const keys = Object.keys(data[0])
let res = {}
for(key of keys)
res[key]=data.map(x=>x[key]).reduce((a,b)=>a+b);
return res
}
console.log(sum(items))
Here is an alternative, simple, and clean solution for this.
const items = [{amount1:100, amount2:50, name:"ruud"},{amount1:40,amount2:60,name:"ted"}]
let result = [{amount1:0,amount2:0}]
items.forEach(i=>{
result[0].amount1 += i.amount1
result[0].amount2 += i.amount2
})
console.log(result)
Above solutions are great. I included this if you don't want to use
Array.prototype.reduce(). This will work even if you have other properties which are not "numbers"
const items = [{amount1: 100, amount2: 50, name: 'Ruud'}, {amount1: 40, amount2: 60, name: 'Ted'}];
var result = {};
items.forEach(function(eachItem){
for(var prop in eachItem){
if(typeof eachItem[prop] === "number"){
result[prop] = result[prop] ? result[prop] + eachItem[prop] : eachItem[prop];
}
}
});
result = [result];
console.log(result);
You can use reduce().
Use the reduce() method on the array items
Set the accumulator(ac) as an empty object i.e {}
During each iteration through the objects create a for..in loop to iterate through all keys of object.
Check if the typeof value of key is "number" then add it otherwise don't
const items = [{amount1:100, amount2:50, name:"ruud"}, {amount1:40,amount2:60,name:"ted"}]
let res = [items.reduce((ac,x) => {
for(let key in x){
if(typeof x[key] === "number"){
if(!ac[key]) ac[key] = 0;
ac[key] += x[key]
}
}
return ac;
},{})]
console.log(res)
reduce() is indeed the way to go, but the cleanest to go only through a set of known keys is probably to pass your expected result as the accumulator and to iterate over this accumulator's keys:
const items = [
{ amount1: "100", amount2: "50", name: "ruud", foo: "unrelated" },
{ amount1: "40", amount2: "60", name: "ted", foo: "0" }
];
const result = items.reduce((acc, item) => {
for (let key in acc) { // iterate over the accumulator's keys
acc[key] += isNaN(item[key]) ? 0 : +item[key];
}
return acc;
}, { // here we define the expected format
amount1: 0,
amount2: 0
});
console.log(result);

A more efficient way to rearrange Array of Objects?

Hello fellow good devs,
I want to rearrange this the Array of objects (array1) into the same order given in array2; as you may have noticed below, array2 is a simple array which its values are the same key names in array1, so you can say array2 is the 'arranging reference' for array1.
The below code worked for me as expected, but I am not happy with it, so much loops inside loops, i am afraid it may not be efficient.
I thought of using map() but I couldn't figure out how, is there any more efficient way for doing that by using map() or some other method?
Note: This is a server-side code, so I am not concerned about Browser compatibility.
var array1 =
[
{ 'aaa': '1000', 'bbb': '2000' },
{ 'aaa': '3333', 'bbb': '4444' }
]
var array2 = ['bbb', 'aaa'];
var reArrangedArr = [];
array1.forEach(x => {
var obj = {};
for (i = 0; i < array2.length; i++) {
for (key in x) {
console.log(array2[i] + " " + key)
if (array2[i] === key) {
newKey = array2[i];
console.log("equal");
obj[newKey] = x[key]
}
}
}
reArrangedArr.push(obj);
});
console.log(reArrangedArr);
///output: > Array [Object { bbb: "2000", aaa: "1000" }, Object { bbb: "4444", aaa: "3333" }]
You could map the array and map with Object.assign the keys and their values in the wanted order.
With spread syntax ..., a given iterable, like an array or string, is treated as parameters for the function call. Basically it is a syntactic suggar for function.apply(this, array).
var data = [{ aaa: '1000', bbb: '2000' }, { aaa: '3333', bbb: '4444' }],
keys = ['bbb', 'aaa'],
reordered = data.map(o => Object.assign(...keys.map(k => ({ [k]: o[k] }))));
console.log(reordered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use Array.reduce() operation to achieve that:
var array1 = [
{ 'aaa': '1000', 'bbb': '2000' },
{ 'aaa': '3333', 'bbb': '4444' }
];
var array2 = ['bbb', 'aaa'];
var reArrangedArr = array1.reduce((acc, obj) => {
var tempObj = {};
array2.forEach(item => tempObj[item] = obj[item]);
acc.push(tempObj);
return acc;
},
[]);
console.log(reArrangedArr);

Converting an array of 3 arrays into 1 big array with object variable

I'm new to StackOverflow and I know this post might possibly be a duplicate of another so please spare me with all the downvotes and if you think there's an answer to my question out there, please post it and I'll delete this question. Thanks for understanding.
var array1 = ["name", "title", "desc"]
var array2 = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]]
How will I turn these into:
[
{name: "name1", title: "title1", desc: "desc1"},
{name: "name2", title: "title2", desc: "desc2"}
]
You can use Array#map, Object.assign (with spread syntax) and the ES6 computed property syntax to achieve that:
const array1 = ["name", "title", "desc"],
array2 = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]];
const result = array2[0].map( (_, j) =>
Object.assign(...array1.map( (key, i) => ({ [key]: array2[i][j] }) ))
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const result = [];
for(const [index, key] of array1.entries()){
for(const [userindex, value] of array2[index].entries()){
if(!result[userindex])
result[userindex] = {};
result[userindex][key] = value;
}
}
You might go over every key and the values related to the key and assign every key/value pair to the resulting object at the position of the value.
You could reduce the given values array by using the keys as key and the value for new objects.
var keys = ["name", "title", "desc"],
values = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]],
objects = values.reduce((r, a, i) => {
a.forEach((v, j) => Object.assign(r[j] = r[j] || {}, { [keys[i]]: v }));
return r;
}, []);
console.log(objects);
You can use this way also:
var array1 = ["name", "title", "desc"];
var array2 = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]];
var res = [];
for(var i=0; i<array2[0].length; i++){
var obj = {};
for(var j=0; j<array1.length; j++){
var key = array1[j];
var value = array2[j][i];
obj[key] = value;
}
res.push(obj);
}
console.log(res);

Categories

Resources