I have an array :
const data = [{"label": "a", "value": 4}, {"label": "b", "value": 1}, {"label": "c", "value": 2}]
I want to create a new array of objects where I have to give key and value in it.
For eg,:
const newArr = [{1,4},{2,1},{3,2}]
here first item of an object is the key, which has to increase as the number of objects increase, and second item is the value from data.
const data = [{"label": "a", "value": 4}, {"label": "b", "value": 1}, {"label": "c", "value": 2}];
const out = data.map((item, index) => [index + 1, item.value]);
console.log(out);
I hope this is your solution:
const data = [
{
label: 'a',
value: '4'
},
{
label: 'b',
value: '1'
},
{
label: 'c',
value: '2'
},
]
const newArrOfObj = data.reduce((arr, current, index)=> [...arr, {[index+1]:current.value}], []);
console.log(newArrOfObj) //[ { 1: '4' }, { 2: '1' }, { 3: '2' } ]
To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr.push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.
index.js
let arr = [];
const obj = {name: 'Tom'};
arr.push(obj);
console.log(arr); // 👉️ [{name: 'Tom'}]
Related
I have this array which holds objects;
let arr = [
{
"id": 1,
"level": "2",
},
{
"id": 2,
"level": "3",
}
]
By default the array has keys starting from 0 and it looks like this:
[
0: {id: 1, level:2},
1: {id: 2, level:3}
]
How can I transform it so that the keys are the values of the property 'level'?
It should look like this:
[
2: {id:1, level:2},
3: {id:1, level:3}
]
So far I have tried this but it doesn't remove the original keys:
arr.map((v, k) => ({[v.level]: v}));
So I have something like this:
[
0: {2:
{id: 1, level:2}
},
1: {3:
{id: 2, level:3}
}
]
You need to populate a new array using reduce:
arr.reduce((prev, curr) => { prev[curr.level] = curr; return prev }, [])
I think I prefer the reduce method, but you could also construct an "array-like" (i.e. an object with numeric keys and a length property) and pass it to Array.from
const maxIdx = Math.max(...arr.map(v => parseInt(v.level, 10)))
const arrLen = maxIdx + 1;
const arrayLike = {
...Object.fromEntries(arr.map(v => [v.level, v])),
length: arrLen
};
const mappedArray = Array.from(arrayLike);
For output of
[undefined, undefined, {
"id": 1,
"level": "2"
}, {
"id": 2,
"level": "3"
}]
If I have the following
arr = [
{key: "a",
values : [{key: "aa", value: 2}, {key: "bb", value: 5}]},
{key: "b",
values : [{key: "cc", value: 7}, {key: "dd", value: 3}]}
]
How to use reduce in javascript to find the maximum from the nested objects? The answer should be 7 in the above case.
I currently am able to use a loop to achieve this:
let max = 0;
let findDataMax = function(d) {
for (let i = 0; i < d.length; i++) {
let currArr = d[i].values;
let tempArr = []
currArr.forEach((d) => tempArr.push(+d.value));
if (Math.max(...tempArr) > max) {
max = Math.max(...tempArr);
}
}
}
let arr = [
{key: "a", values : [{key: "aa", value: 2}, {key: "bb", value: 5}]},
{key: "b",values : [{key: "cc", value: 7}, {key: "dd", value: 3}]}
];
findDataMax(arr);
console.log(max);
I would prefer to use other methods other than reduce for this, but if you have to, then you can set the accumulator as -Infinity to begin with (this way any value compared with the accumulator will be bigger than -Infinity). For each object in your array, you can find the max by mapping the array of values to an array of value numbers from each object, and then spreading these numbers into a call to Math.max(). You can then compare whether or not this is larger than the current maximum, and if it is, return that as the new value to use as the accumulator, otherwise, use the old accumulator value:
const arr = [ {key: "a", values : [{ key: "aa", value: 2}, { key: "bb",value: 5}]}, {key: "b", values : [{ key: "cc", value: 7}, { key: "dd", value: 3}]} ];
const max = arr.reduce((max, {values}) => {
const newMax = Math.max(...values.map(({value}) => value));
return newMax > max ? newMax : max;
}, -Infinity);
console.log(max);
As previously mentioned, I would probably use a different approach to .reduce(), such as .flatMap() to grab all object value numbers, which you can then spread into a call to Math.max():
const arr = [ {key: "a", values : [{ key: "aa", value: 2}, { key: "bb",value: 5}]}, {key: "b", values : [{ key: "cc", value: 7}, { key: "dd", value: 3}]} ];
const max = Math.max(...arr.flatMap(({values}) => values.map(({value}) => value)));
console.log(max);
I don't know if the use of the reduce function is a clean solution for this problem but here you have it:
const arr = [{ key: 'a', values: [{ key: 'aa', value: 2 }, { key: 'bb', value: 5 }] }, { key: 'b', values: [{ key: 'cc', value: 7 }, { key: 'dd', value: 3 }] }];
// O(n * b)
const maxValue = arr.reduce((prev, item) => item
.values.reduce((subPrev, subItem) => (subItem.value > subPrev ? subItem.value : subPrev), prev), 0);
console.log(maxValue); // 7
I have an array of key/value pairs. The keys are sometimes duplicated, and the values are always unique per key.
I want to condense each unique key to an object, so that I have a key and an array of the associated values as a property.
Are there any handy javascript functions to do this?
This
pairArray = [
{ key: "a", value: "1" },
{ key: "a", value: "2" },
{ key: "b", value: "1" },
{ key: "b", value: "2" },
];
Becomes
objectArray = [
{ key: "a", values: ["1", "2"] },
{ key: "(", values: ["1", "2"] }
];
You can simply create a map using Array.reduce() with your key property of your object as key of your map, Object.values() on that map will give you the desired result :
Assuming you have a typo in your expected output. You can try the following :
const pairArray = [ { key: "a", value: "1" }, { key: "a", value: "2" }, { key: "b", value: "1" }, { key: "b", value: "2" }, ];
const result = Object.values(pairArray.reduce((acc, {key, value})=>{
acc[key] = acc[key] || {key, values : []};
acc[key].values.push(value);
return acc;
},{}));
console.log(result);
You can use Map() to get the desired output:
let data = [
{ key: "a", value: "1" },
{ key: "a", value: "2" },
{ key: "b", value: "1" },
{ key: "b", value: "2" },
];
let reducer = arr => {
let map = new Map();
arr.forEach(({key:k, value:v}) => {
let values = map.get(k) || [];
values.push(v);
map.set(k, values);
});
return [...map.entries()].map(([k, v]) => ({key: k, values: v}));
};
console.log(reducer(data));
I'm trying to achieve something like this:
let obj = [
{"id": "1"},
{"id": "2"},
{"id": "3"}
]
const arr = ["a", "b", "c"];
obj = addAtoO(arr, obj); // expected outcome: obj = [{"id": "1", "text": "a"}, {"id": "2", "text": "b"}, {}]
In words: dynamically add values from an array to an object as new values.
Here's what I'm trying:
const addAtoO = (a, o) => {
o.map((i) => {
console.log(Object.keys(i));
// a.forEach((e) => {
// console.log(e);
// });
i['text'] = 'something'; // just add text for testing
});
return o;
};
obj = addAtoO(arr, obj);
console.log('result:');
console.log(obj);
But it seems like there must be a better way.
Thank you so much guys. All your solutions are correct. I had to mark one so I picked the one that is the closest to this specific question.
You can use map as you are using , & use it's index to get the value from arr array and create a new object with values from obj & arr
let obj = [{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
const arr = ["a", "b", "c"];
let output = obj.map(function(item, index) {
return Object.assign({}, item, {
text: arr[index]
})
})
console.log(output)
Else you can also use forEach and mutate the original obj array
let obj = [{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
const arr = ["a", "b", "c"];
obj.forEach(function(item, index) {
item.text = arr[index]
})
console.log(obj)
The way you are using addAtoO suggests that you don't care about altering the original objects. If that's the case, then a simple forEach will do:
const addAtoO = (arr, obj) => arr.forEach((t, i) => obj[i].text = t);
addToO alters the original array of objects obj, so it doesn't return anything.
Example:
const addAtoO = (arr, obj) => arr.forEach((t, i) => obj[i].text = t);
let obj = [ {"id": "1"}, {"id": "2"}, {"id": "3"}];
const arr = ["a", "b", "c"];
addAtoO(arr, obj);
console.log(obj);
You can use .map() like this:
const arr1 = [
{"id": "1"},
{"id": "2"},
{"id": "3"}
]
const arr2 = ["a", "b", "c"];
const merge = (a1, a2) => a1.map((o, i) => Object.assign({}, o, {text: a2[i]}));
console.log(merge(arr1, arr2));
.as-console-wrapper { max-height: 100% !important; top: 0; }
For more flexibility, i suggest to use a key for the function as well as parameter.
const addTo = (objects, values, key) =>
objects.map((o, i) => Object.assign({}, o, { [key]: values[i] }));
console.log(addTo([{ id: "1" }, { id: "2" }, { id: "3" }], ["a", "b", "c"], 'text'));
If you like to mutate the given objects, just remove the empty object from Object.assign.
const addTo = (objects, values, key) =>
objects.map((o, i) => Object.assign(o, { [key]: values[i] }));
var objects = [{ id: "1" }, { id: "2" }, { id: "3" }];
addTo(objects, ["a", "b", "c"], 'text');
console.log(objects);
There is no need to make things complicated. Just use a forEach.
let obj = [{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
const arr = ["a", "b", "c"];
obj.forEach((object, index) => {
object.text = arr[index]
})
console.log(obj)
I am learning array filter,reduce and map methods. while doing some exercises I got struct. I have array of object like this
var p=[
{
"key": "a",
"value": 4
},
{
"key": "b",
"value": 3
},
{
"key": "c",
"value": 3
},
{
"key": "d",
"value": 6
},
{
"key": "e",
"value": 1
}
]
and this what I did
var column=p.reduce((accumulator, currentValue, currentIndex, array)=>{
var arr=[];
arr[currentValue.key]=currentValue.value;
console.log(accumulator)
return (accumulator.push(arr));
},[])
console.log(column)
and I am expecting array like this
[['a',4],['b',3],['c',3],['d',6],['e',1]]
after first iteration I got this error:
accumulator.push is not a function
I don't know what I am doing wrong.
Getting [['a',4],['b',3],['c',3],['d',6],['e',1]]
Using .reduce
This is what you've used in your code. The problem with your code is that your accessing an index that doesn't exist in arr, because on the previous line you set arr to an empty array. You don't need to have the array arr inside the reduce loop. You should push the value directly to the accumulator
The reduce() method applies a function against an accumulator
const res = p.reduce((acc, curr) => {
acc.push([curr['key'], curr['value']]);
return acc;
}, []);
const p = [ {"key": "a", "value": 4}, {"key": "b", "value": 3}, {"key": "c", "value": 3}, {"key": "d", "value": 6}, {"key": "e", "value": 1} ];
const res = p.reduce((acc, curr) => {
acc.push([curr['key'], curr['value']]);
return acc;
}, []);
console.log(res)
//[['a',4],['b',3],['c',3],['d',6],['e',1]]
Using .map
You can also achieve this same result using a the .map method instead:
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
const res = p.map(e => [e['key'], e['value']]);
const p = [ {"key": "a", "value": 4}, {"key": "b", "value": 3}, {"key": "c", "value": 3}, {"key": "d", "value": 6}, {"key": "e", "value": 1} ];
const res = p.map(e => [e['key'], e['value']])
console.log(res)
//[['a',4],['b',3],['c',3],['d',6],['e',1]]
Getting { 'a': 4, 'b': 3, 'c': 3, 'd': 6, 'e': 1 }
You can use objects instead of having an array for each key/value pairs. This way you can assign a value to a key and get the desired result:
{key: value, ...}
In your case:
{ 'a': 4, 'b': 3, 'c': 3, 'd': 6, 'e': 1 }
Using .reduce
You could do this with the .reduce method:
const obj = p.reduce((acc, curr) => {
acc[curr['key']] = curr['value'];
return acc;
}, {});
const p = [ {"key": "a", "value": 4}, {"key": "b", "value": 3}, {"key": "c", "value": 3}, {"key": "d", "value": 6}, {"key": "e", "value": 1} ];
const obj = p.reduce((acc, curr) => {
acc[curr['key']] = curr['value'];
return acc;
}, {});
console.log(obj)
Using .forEach
Or with a simple .forEach loop:
The forEach() method executes a provided function once for each array element.
let obj = {};
p.forEach(e => obj[e['key']] = e['value']);
const p = [ {"key": "a", "value": 4}, {"key": "b", "value": 3}, {"key": "c", "value": 3}, {"key": "d", "value": 6}, {"key": "e", "value": 1} ];
let obj = {};
p.forEach(e => obj[e['key']] = e['value']);
console.log(obj);
Your result will be an array of objects, not an array of arrays. While you can fix your implementation to work with reduce() it is much simpler to do it with map():
var new_p = p.map(obj => {{[obj.key]: obj.value}});
If you want a single object instead an array of objects, you can use reduce():
var new_p p.reduce((acc, obj) => {
acc[obj.key] = obj.value;
return acc;
}, {});
This assumes that all of the keys are unique. If any key is repeated, you will only get the last value for that key.
You can use map to loop thru the array and return the new object.
var p = [{"key":"a","value":4},{"key":"b","value":3},{"key":"c","value":3},{"key":"d","value":6},{"key":"e","value":1}];
var result = p.map(({key,value}) => ({[key]:value}));
console.log(result);
If you want to create a new object, you can use Object.assign() and map()
var p = [{"key":"a","value":4},{"key":"b","value":3},{"key":"c","value":3},{"key":"d","value":6},{"key":"e","value":1}];
var result = Object.assign(...p.map(o => ({[o.key]:o.value})));
console.log( result );
Doc: map(), Object.assign()
You can use Array.prototype.map() combined with Object.values()
Code:
const p = [{"key": "a","value": 4},{"key": "b","value": 3},{"key": "c","value": 3},{"key": "d","value": 6},{"key": "e","value": 1}];
const result = p.map(o => Object.values(o));
console.log(result);