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 1 year ago.
Improve this question
I need to assign the values of the below array of objects into defined variables which are initialized as empty strings.
What I have tried up until now:
const transaction = [{
number: 10,
value: "Ten"
},
{
number: 20,
value: "Twenty"
},
];
let transactionOneValue, transactionTwoValue, transactionOneNumber, transactionTwoNumber = "";
if (transaction.length > 0) {
transaction.forEach(item => {
[transactionOneNumber, transactionTwoNumber].forEach(num => num = item.number);
[transactionOneValue, transactionTwoValue].forEach(val => val = item.value);
});
}
Expected output:
transactionOneValue = "Ten",
transactionTwoValue = "Twenty",
transactionOneNumber = 10,
transactionTwoNumber = 20
How can I do it?
Destructuring seems to be simplest approach here, but I don't see how this would be useful. Creating separate variables for every item in a list isn't scalable.
let [
{number: transactionOneNumber, value: transactionOneValue},
{number: transactionTwoNumber, value: transactionTwoValue}
] = transaction
const transaction = [{
number: 10,
value: "Ten"
},
{
number: 20,
value: "Twenty"
},
];
let transactions = [];
if (transaction.length > 0) {
transaction.map((value, index, array) => {
for(x of Object.values(value)) {
transactions.push(x);
}
})
}
let transactionOneNumber = transactions[0],
transactionOneValue = transactions[1],
transactionTwoNumber = transactions[2],
transactionTwoValue = transactions[3];
console.log(transactionOneNumber);
console.log(transactionOneValue);
console.log(transactionTwoNumber);
console.log(transactionTwoValue);
output:
10
"Ten"
20
"Twenty"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
Related
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 24 days ago.
Improve this question
So basically I have an array of ids and I want to return only a simple array which I want to look like this
*[1,2,3]*
instead of
*[0:[1] , 1:[2]]*
Is there any way to do it
Code
const usersWhoHavePurchasedYourCourses = usersWhoHaveTokens.filter(
(user1: any) => {
return user1.tokens
?.map((token: any) => parseInt(token.course_id))
.includes(user.courses?.map((course: any) => course.id));
});
The output looks like this
output
As I said I don`t want to return this kind of output.
Edit
In attempting to reverse-engineer your logic, wouldn't you want to filter by checking if a user has at least one course? I recommend using Array.prototype.some as your filter result.
const user = { courses: [{ id: 1 }, { id: 2 }] };
const usersWhoHaveTokens = [
{ id: 1, tokens: [{ course_id: '1' }] },
{ id: 2, tokens: [{ course_id: '2' }] },
{ id: 3, tokens: [{ course_id: '3' }] },
];
// Compute the set, for faster processing
const userCourseIds = new Set(user.courses.map((course) => course.id));
const usersWhoHavePurchasedYourCourses = usersWhoHaveTokens
.filter(({ tokens }) => tokens
.some((token) => userCourseIds.has(parseInt(token.course_id))))
.map(({ id }) => id);
console.log(usersWhoHavePurchasedYourCourses); // [1, 2]
Original response
If you object is an 'object' type, you will need to transform it into an array, and then flatten it.
const
obj = { 0: [1], 1: [2] },
arr = Object.values(obj).flat();
console.log(JSON.stringify(arr)); // [1, 2]
If you want to preserve indices:
const
obj = { 1: [2], 5: [6] },
arr = Object.entries(obj).reduce((acc, [index, value]) => {
acc[+index] = value;
return acc;
}, []).map(([value]) => value);
console.log(JSON.stringify(arr)); // [null, 2, null, null, null, 6]
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 7 months ago.
Improve this question
i have this array
const names = [
{ name: 'Anna' },
{ num: 27 },
{ name: 'Valeria', age: 20},
{ secondname: 'Wilson' },
{ age: 12, name: 'Max' },
{ weight:'50kg', height: '172cm', name: 'Nick' }
]
using reduce i need to create new array that contains all names from initial array
i made like this, but i think it is bad
let allNames = names.reduce((previousValue, names) =>{
return previousValue + names.name},[])
console.log(allNames)
i did
allName.push(ar.name);
return allName;
}, []);
console.log(names);```
Array.reduce()
You have multiple options. You can use Array.reduce to merge them all into one array. You just need to check if name is defined.
names.reduce((allNames, person) => {
if (person.name) {
return [...allNames, person.name];
}
return allNames;
}, []);
Array.forEach()
Same for Array.forEach:
const allNames = [];
names.forEach((person) => {
if (person.name) {
allNames.push(person.name);
}
});
allNames;
Instead, I would recommend using Array.filter to remove all people without a name and map (Array.map) over them, to just return the names.
In terms of runtime, this would require you to loop twice over the array, but I think this is way more readable
Array.filter / Array.map
names
.filter((person) => person.name)
.map((person) => person.name);
Using reduce by including a check for objects that don't have the name property and an empty array as initial value:
const names = [
{ name: 'Anna' },
{ num: 27 },
{ name: 'Valeria', age: 20},
{ secondname: 'Wilson' },
{ age: 12, name: 'Max' },
{ weight:'50kg', height: '172cm', name: 'Nick' }
]
const reduceResult = names.reduce((previous, current) => {
if(current.name)
{
previous.push(current.name);
}
return previous;
}
,
[]);
console.log(reduceResult);
/*
[
"Anna",
"Valeria",
"Max",
"Nick"
]
*/
Using map, you will have undefined for objects that don't have a name property:
const mapResult = names.map(x => x.name);
console.log(mapResult);
/*
[
"Anna",
undefined,
"Valeria",
undefined,
"Max",
"Nick"
]
*/
filter + map can also be used but performance talking reduce is a better choice.
const filterMapResult = names.filter(({name}) => !!name).map(x => x.name);
console.log(filterMapResult);
/*
[
"Anna",
"Valeria",
"Max",
"Nick"
]
*/
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 1 year ago.
The community is reviewing whether to reopen this question as of 1 year ago.
Improve this question
I have two array:
arrayA = ["Apple", "Banana", "Orange"]
arrayB = [1, 2, 3]
I need to make an object with these two array, but having custom keys.
Output desired:
{
{
id: 1,
name: "Apple"
},
{
id: 2,
name: "Banana"
},
{
id: 3,
name: "Orange"
}
}
what I have tried:
I have following some SO answer and it didnt meet my requirements:
result = {};
arrayA.forEach((item, i) => {
result["id"] = arrayB[i];
result["name"] = item;
});
the above code just reassign the value to the last item, hence I only got one object like this:
{
id: 3,
name: "Orange"
}
Just use map instead
const arrayA = ["Apple", "Banana", "Orange"];
const arrayB = [1, 2, 3];
const newArray = arrayA.map((item, i) => {
return {
"id" : arrayB[i],
"name" : item
}
});
console.log(newArray);
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 have an object like this
{ '2020-08': {Invoice: 21400, Receipt: 20800, ...},
'2020-09': {Invoice: 8003.6, ...},
'2020-10': {Receipt: 7779.2, ...},
'2020-11': {Invoice: 32970, ...}
}
Wanna make it to be 2d array like this
[ ['2020-08', '2020-09', '2020-10', '2020-11'],
[ 21400 , 8003.6 , 0 , 32970 ], //Invoice
[ 20800 , 0 , 7779.2 , 0 ], //Receipt
...
]
It is very easy to achieve using Object.keys.
const data = {
'2020-08': {
Invoice: 21400,
Receipt: 20800
},
'2020-09': {
Invoice: 8003.6,
Receipt: 7779
},
'2020-10': {
Receipt: 7779.2,
Invoice: 32970
},
'2020-11': {
Invoice: 32970,
}
}
const res = []
const keys = [...Object.keys(data)]
const d = Object.keys(data).map(item => {
return data[item]["Invoice"] || 0
})
const d1 = Object.keys(data).map(item => {
return data[item]["Receipt"] || 0
})
console.log([keys, d, d1])
Try:
let result = [], key= [], invoice= [], receipt = [];
Object.keys(obj).forEach((x) => {
key.push(x);
invoice.push(obj[x].Invoice || 0);
receipt.push(obj[x].Receipt || 0);
});
result = [key,invoice,receipt];
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 2 years ago.
Improve this question
I have two array
arr1 = ["google.com", "none", "Twitter", "Facebook"]
arr2 = [6, 25, 1, 8]
Then my expected output would be like this
newArr = [
{
'medium': 'www.google.com',
'key': 6
},
{
'medium': 'none',
'key': 25
},
{
'medium': 'Twitter',
'key': 1
},
{
'medium': 'Facebook',
'key': 8
}
];
I have tried something like this but did not get the expected output
const result = arr1.reduce(function(result, field, index) {
result[arr2[index]] = field;
return result;
});
How can I achieve the output? Thanks.
You could do a map with index
const arr1 = ["google.com", "none", "Twitter", "Facebook"]
const arr2 = [6, 25, 1, 8]
const res = arr1.map((_, index) => ({
medium: arr1[index],
key: arr2[index],
}))
console.log(res)
This should work assuming arr1 and arr2 length always equal
function combineTwoArrays (arr1, arr2){
let result = []
for (let i = 0; i< arr1.length; i++){
result.push({
medium: arr1[i],
key: arr2[i]
})
}
return result
}