How to join two separate arrays into one array? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I do have two different arrays namely,
["Laddoo", "Sweets", "Mixtures", "1FixBoxes", "Chips"]
[120, 185, 150, 145, 130]
I need to Join them as a single array like this.
data: [
{
name: 'Laddoo',
y: 120,
},
{
name: 'Sweets',
y: 185
},
{
name: 'Mixtures',
y: 150
},
{
name: '1FixBoxes',
y: 145
},
{
name: 'Chips',
y: 130
}
]

You can use Array.map()
const names = ["Laddoo", "Sweets", "Mixtures", "1FixBoxes", "Chips"];
const yValues = [120, 185, 150, 145, 130];
const transformedData = names.map((name, index) => ({name: name, y: yValues[index]}));
console.log(transformedData);

Call .map on either array and use the index to get the value of the other array.
nameArray.map((val, index) => { name: val, y: yArray[index] });

Related

delete and modify properties in array inside json object [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 12 months ago.
Improve this question
Given the following JSON:
const myJson = {
id: 8,
active: true,
invoice: "2022/1001",
invoiceDate: "2022-02-02",
clientId: 1,
storeId: 1,
total: 76.95,
itens: [
{
id: 11,
quantity: 2,
price: 12.10,
total: 24.20,
productId: 1,
invoiceId: 8
},
{
id: 12,
quantity: 5,
price: 10.55,
total: 52.75,
productId: 2,
invoiceId: 8
}
]
};
I need a simple way to remove two attributes from the each item inside the 'itens' array, the properties are 'id' and 'invoiceId'. I also need to recalculate the 'total', coz I do not trust totally the source of the information, I rather multiply 'quantity' by 'price' myself.
I've produced this rather naive code:
myJson.itens.forEach(item => {
item.total =
item.quantity *
item.price;
delete item.id;
delete item.invoiceId;
});
And it works rather fine, however, no way that it must be it. Looks too lame and laborious to me. I'm exhausted googling for better ways of doing it.
Can it be done better?
Rather than mutating the original data, you could map it to a new object
const myJson = {"id":8,"active":true,"invoice":"2022/1001","invoiceDate":"2022-02-02","clientId":1,"storeId":1,"total":76.95,"itens":[{"id":11,"quantity":2,"price":12.1,"total":24.2,"productId":1,"invoiceId":8},{"id":12,"quantity":5,"price":10.55,"total":52.75,"productId":2,"invoiceId":8}]}
const newObject = {
...myJson, // keep the rest but map "itens"
itens: myJson.itens.map(({ id, invoiceId, ...iten }) => ({
...iten, // everything except "id" and "invoiceId"
total: iten.quantity * iten.price // recalc total
}))
}
console.log("newObject:", newObject)
.as-console-wrapper { max-height: 100% !important; }

Adding an incrementing number to each object in an array of objects with Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Say I have an array of objects:
const myArray = [{ color: 'red' }, { color: 'blue'}, { color: 'yellow'}]
How can I expand the object to add a key value pair to each element where the key is number and the value is a number that increments by one in each object? My desired outcome is:
const myNewArray = [{ color: 'red', number: 1 }, { color: 'blue', number: 2 }, { color: 'yellow', number: 3 }]
const myNewArray = myArray.map((item, index) => { return {"number" :index, ...item} } )

How to get highest 3 value from object array - ES6/JS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I simply want to get 3 highest price value objects as new array. How would I do that easily ?
For example i got array like this ..
const data =
[ { name: 'x', color: 'red', price: 15 }
, { name: 'y', color: 'black', price: 5 }
, { name: 'z', color: 'yellow', price: 25 }
, { name: 't', color: 'blue', price: 10 }
, { name: 'n', color: 'blue', price: 60 }
]
You can sort the array by the price property (with Array.sort) and get the first three items (with Array.slice):
const arr=[{name:"x",color:"red",price:15},{name:"y",color:"black",price:5},{name:"z",color:"yellow",price:25},{name:"t",color:"blue",price:10},{name:"n",color:"blue",price:60}];
const result = arr.sort((a,b) => b.price - a.price).slice(0, 3)
console.log(result)

How to create array out of object entries? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need help creating a JavaScript object:
I have three fields from the input form in React state object:
{
calories: "45",
fats: "56",
proteins: "67"
}
I would like to create a new array i.e. nutrientInformation from this data. The output should resemble this:
nutrientInformation: [
{
calories: 45
},
{
fats: 56
},
{
proteins: 67
}
]
const state = { calories: "45", fats: "56", proteins: "67" };
const nutrientInformation = Object.entries(state).map(([key, value]) => ({
[key]: value
}));
console.log(nutrientInformation);

JS array : filter() with map() vs forEach() [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 12 months ago.
Improve this question
Which is more optimized way .filter() + .map() OR .forEach() ?
Here is a sample array of objects:
var personnel = [
{
id: 5,
name: "Luke Skywalker",
pilotingScore: 98,
shootingScore: 56,
isForceUser: true,
},
{
id: 82,
name: "Sabine Wren",
pilotingScore: 73,
shootingScore: 99,
isForceUser: false,
},
{
id: 22,
name: "Zeb Orellios",
pilotingScore: 20,
shootingScore: 59,
isForceUser: false,
},
{
id: 15,
name: "Ezra Bridger",
pilotingScore: 43,
shootingScore: 67,
isForceUser: true,
},
{
id: 11,
name: "Caleb Dume",
pilotingScore: 71,
shootingScore: 85,
isForceUser: true,
},
];
And let say we want to get the final array giving only name and id where isForceUser=true
[ { id: 5, name: 'Luke Skywalker' }, 
{ id: 15, name: 'Ezra Bridger' }, 
{ id: 11, name: 'Caleb Dume' } ] 
Now there are 2 ways ti solve it :
By using .filter()+.map(), as shown below:
var APersonnel = personnel
.filter((person) => person.isForceUser)
.map((person) => ({ id: person.id, name: person.name }));
By using .forEach() and pushing a new object:
var BPersonnel = [];
personnel.forEach((person) => {
if (person.isForceUser) {
BPersonnel.push({ id: person.id, name: person.name });
}
});
Which one of the solutions defined above is better and why?
These are not the things you should seek performance improvements in. You are talking about 'personnel' here. Which is a fairly limited array set, I imagine. If you are having performance issues, I suggest you use the chrome dev performance tab to see what's causing it.
To answer your question, filter + map is semantically easier for the eye, which again is a personal opinion. Strictly performance wise the forEach is faster, where most likely a basic of for loop is even faster. But again, these are a few milliseconds we are talking about. Which does not justify the cost of rewriting :)
Another way can be to use reduce, less code, and only one loop:
const APersonnel = personell.reduce((acc, person) => {
if (person.isForceUser) {
acc.push({ id: person.id, name: person.name });
}
return acc;
}, []);
The best way is using foreach. Because map and filter are going to create two arrays. foreach doesn't create arrays. So foreach is the best one. look at those statements bellow,
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
I could be wrong, but I'm guessing forEach would be better.
In the first scenario, you are looping across 5 items, and then again across 3 items.
In the second scenario you are just looping across 5 items. And the if in the foreach is effectively being done in the filter anyway.
There may be an exception if you're working with an extremely large set of data because you would have both arrays in memory, but for anything short of that, I would recommend forEach

Categories

Resources