I want to filter an array object, into a separate individual variable with array?
// The given array
const dummy = [
{
id: 1,
name: 'John',
},
{
id: 2,
name: 'Jane',
},
{
id: 3,
name: 'Jane',
},
]
// Expected Output
// let number = [1,2]
// let name = ["John", "Jane"]
CodePudding user response:
You can use Set to get unique values from the original arrays, otherwise .map
is enough.
const dummy = [
{
id: 1,
name: 'John',
},
{
id: 2,
name: 'Jane',
},
{
id: 3,
name: 'Jane',
},
];
const ids = [...new Set(dummy.map(x => x.id))];
const names = [...new Set(dummy.map(x => x.name))];
CodePudding user response:
const dummy = [
{
id: 1,
name: 'John',
},
{
id: 2,
name: 'Jane',
},
{
id: 3,
name: 'Jane',
},
]
let num = []
let names = []
dummy.forEach((element) => {
num.push(element.id)
if(!names.includes(element.name))
names.push(element.name)
})
console.log(num)
console.log(names)
CodePudding user response:
const dummy = [
{
id: 1,
name: 'John',
},
{
id: 2,
name: 'Jane',
},
{
id: 3,
name: 'Jane',
},
]
let number = [];
let name = [];
number.push(dummy[0].id, dummy[1].id);
name.push(dummy[0].name, dummy[1].name);
console.log(number);
console.log(name);
Output:
[ 1, 2 ]
[ 'John', 'Jane' ]
If you having a long array you can use a for-loop as well.
let number = [];
let name = [];
for (let itemIndx = 0; itemIndx < dummy.length; itemIndx ) {
if (itemIndx < 2) {
number.push(dummy[itemIndx].id);
name.push(dummy[itemIndx].name);
}
};
console.log(number);
console.log(name);
CodePudding user response:
You can use the reduce function for this kind of tasks. You can define an initial value for the function and then it iterates over every entry of the array. As parameter you have the return value of the previous iterations and the value of the current entry.
const dummy = [
{
id: 1,
name: 'John',
},
{
id: 2,
name: 'Jane',
},
{
id: 3,
name: 'Jane',
},
]
const {id, name} = dummy.reduce((prev, cur) => {
// skip if name is already present
if (prev.name.indexOf(cur.name) > -1) {
return prev
}
return {id: [...prev.id, cur.id], name: [...prev.name, cur.name]}
}, {id: [], name: []})
console.log(id)
console.log(name)
CodePudding user response:
const { numbers, names } = dummy.reduce((prev, curr) => {
prev.numbers.push(curr.id)
prev.names.push(curr.name)
return prev
}, { numbers: [], names: [] })