How to remove key array in javascript by keep default value [closed] - javascript

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
Hi I want to delete key in array
here is my array
const data = [ { id: "2" } , { id: "4" } ]
I want ouput
['2','4']
here is what i try
data.map(function(item) {
//I return only item.id but output still not change
return item.id
})

That's because .map() method returns a new array, it does not alternate the current array. You need to store the returned array in another variable to get the required output like:
const data = [ { id: "2" } , { id: "4" } ]
const res = data.map(x => x.id)
console.log( res )
Or, using same variable:
let data = [ { id: "2" } , { id: "4" } ]
data = data.map(x => x.id)
console.log( data )

Map returns new array and do not alter source array. so you need to assign the result to a new variable.
const data = [{
id: "2"
}, {
id: "4"
}];
const output = data.map(function(item) {
return item.id
})
console.log(output)

Something like this? We map the key to a number and return it.
const data = [ { id: "2" } , { id: "4" } ];
var result = Object.keys(data).map(function (key) {
return Number(key);
});
console.log(result);

Related

How to extract numbers from an array [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 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]

Using reduce you need to create a new array that contains all the names from the initial array [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 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"
]
*/

Dynamically assign object values to variable in JavaScript [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 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

re-create an Object to be 2D Array [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 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];

Create an object from array [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 4 years ago.
Improve this question
I'm trying to convert the array to map,
The array looks like :
var array = [{
"id" : 123
}, {
"id" : 456
}, {
"id" : 789
}];
The final object I'm trying to build should look like :
var result = {
"123": { id: 123 } ,
"456": { id: 456 } ,
"789": { id: 789 }
};
Any efficient way to implement it will be appreciated :)
Thanks
var array = [
{
"id": 123,
"otherProp": "true"
},
{
"id": 456,
"otherProp": "false"
},
{
"id": 789,
"otherProp": "true"
}
];
var result = array.reduce(function (acc, cur, i) {
acc[cur.id] = cur;
return acc;
}, {});
console.log(result);
Use javaScript reduce
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
Use reduce
var array = [{
"id" : 123
}, {
"id" : 456
}, {
"id" : 789
}];
var expectedValue = {
"123": { id: 123 } ,
"456": { id: 456 } ,
"789": { id: 789 }
};
var result = array.reduce( (acc, c) => (acc[ c.id ] = c, acc) ,{});
console.log('result : ', result);
console.log('(JSON.stringify(expectedValue) === JSON.stringify(result)) ? ', (JSON.stringify(expectedValue) === JSON.stringify(result)));
.as-console-wrapper { max-height: 100%!important; top: 0; }
Explanation
Use reduce to iterate and initialize the accumulator to {}
Set the key as id of item of every iteration c and value as c itself.

Categories

Resources