reduce an array of objects in javascript - javascript

how can I reduce an array of objects of this type:
[
{id: 1, name: 'jhon', lastname: 'doe', age: 30},
{id: 2, name: 'max', lastname: 'wall', age: 20},
{id: 3, name: 'fer', lastname: 'baneg', age: 15}
]
I need to get a new array just with these values:
[
{id: 1, name: 'jhon'},
{id: 2, name: 'max'},
{id: 3, name: 'fer'}
]

You can use map() method for this with ES6 parameter destructuring.
const data = [{id: 1, name: 'jhon', lastname: 'doe', age: 30},{id: 2, name: 'max', lastname: 'wall', age: 20},{id: 3, name: 'fer', lastname: 'baneg', age: 15}]
const result = data.map(({id, name}) => ({id, name}))
console.log(result)

Related

Get all unique values from objects and assign them into array under correct key

I have an array of objects to be converted to an object with an array of unique values assigned to the same keys.
How can I get this output?
//input
let users = [
{ id: 1, name: "Alan", surname: "Davis", age: 34, isAdmin: 'yes'},
{ id: 2, name: "John", surname: "Doe", age: 35, isAdmin: 'no'},
{ id: 3, name: "Monica", surname: "Bush", age: 25, isAdmin: 'no'},
{ id: 4, name: "Sandra", surname: "Back", age: 23, isAdmin: 'no'},
{ id: 5, name: "Jacob", surname: "Front", age: 34, isAdmin: 'yes'},
];
//output
let unique = {
id: [1, 2, 3 ,4 ,5],
name: ['Alan', 'John', 'Monica', 'Sandra', 'Jacob'],
surname: ['Davis', 'Doe', 'Bush', 'Back', 'Front'],
age: [34, 35, 25, 23],
isAdmin: ['yes', 'no'],
}
You can use Array.prototype.reduce() and for all of the items iterate over with Array.prototype.forEach() and creating a unique array with Set
Code:
const users = [{ id: 1, name: 'Alan', surname: 'Davis', age: 34, isAdmin: 'yes' },{ id: 2, name: 'John', surname: 'Doe', age: 35, isAdmin: 'no' },{ id: 3, name: 'Monica', surname: 'Bush', age: 25, isAdmin: 'no' },{ id: 4, name: 'Sandra', surname: 'Back', age: 23, isAdmin: 'no' },{ id: 5, name: 'Jacob', surname: 'Front', age: 34, isAdmin: 'yes' },]
const unique = users.reduce((a, c) => (
Object
.entries(c)
.forEach(([k, v]) => a[k] = [...new Set([...(a[k] || []), v])]),
a
), {})
console.log(unique)
Here's one way
Iterate over the keys of the first object in the array to produce a list of keys
Create an array of the corresponding values. Filter the array for dupes.
Wrap the keys and values back into an object
let users = [
{ id: 1, name: "Alan", surname: "Davis", age: 34, isAdmin: 'yes'},
{ id: 2, name: "John", surname: "Doe", age: 35, isAdmin: 'no'},
{ id: 3, name: "Monica", surname: "Bush", age: 25, isAdmin: 'no'},
{ id: 4, name: "Sandra", surname: "Back", age: 23, isAdmin: 'no'},
{ id: 5, name: "Jacob", surname: "Front", age: 34, isAdmin: 'yes'},
];
let unique = Object.fromEntries(
Object.keys(users[0]).map(k =>
[k, users.map(u => u[k]).filter((value, i, arr) => arr.indexOf(value) === i)]
)
);
console.log(unique);

How can I regroup Array of objects by given field

I have given array of objects, something like this
const data = [
{id: 1, name: 'Alex', job: 'IT'},
{id: 2, name: 'Pavel', job: 'IT'},
{id: 3, name: 'Joe', job: 'IT'},
{id: 4, name: 'Josh', job: 'IT'},
{id: 5, name: 'Max', job: 'teacher'},
{id: 6, name: 'Sam', job: 'teacher'}
]
I need array of arrays filtered by field job
const result = [
{job: 'IT',
workersInfo: [
{id:1, name:'Alex'},
{id:2, name:'Pavel'},
{id:3, name:'Joe'},
{id:4, name:'Josh'}
]
},
{job: 'teacher',
workersInfo: [
{id:5, name: 'Max'},
{id:6, name: 'Sam'}
]
}
]
I tried this, but It's not what I want
const data = [
{id: 1, name: 'Alex', job: 'IT'},
{id: 2, name: 'Pavel', job: 'IT'},
{id: 3, name: 'Joe', job: 'IT'},
{id: 4, name: 'Josh', job: 'IT'},
{id: 5, name: 'Max', job: 'teacher'},
{id: 6, name: 'Sam', job: 'teacher'}
]
const groupList = data.reduce((reduce, it) => {
reduce[it.job] = reduce[it.job] || [];
reduce[it.job].push({id: it.id, name: it.name});
return reduce;
}, {})
console.log(Object.values(groupList));
How can I add new key workers Info and push info to this field
If you create a new object on each iteration instead of an array you can then use Object.values:
const data = [
{id: 1, name: 'Alex', job: 'IT'},
{id: 2, name: 'Pavel', job: 'IT'},
{id: 3, name: 'Joe', job: 'IT'},
{id: 4, name: 'Josh', job: 'IT'},
{id: 5, name: 'Max', job: 'teacher'},
{id: 6, name: 'Sam', job: 'teacher'}
];
const groupList = data.reduce((acc, { job, id, name }) => {
acc[job] = acc[job] || { job, workersInfo: [] };
acc[job].workersInfo.push({ id, name });
return acc;
}, {})
console.log(Object.values(groupList));
Example below
const data = [
{ id: 1, name: "Alex", job: "IT" },
{ id: 2, name: "Pavel", job: "IT" },
{ id: 3, name: "Joe", job: "IT" },
{ id: 4, name: "Josh", job: "IT" },
{ id: 5, name: "Max", job: "teacher" },
{ id: 6, name: "Sam", job: "teacher" },
];
const output = data.reduce((acc, o) => {
const index = acc.findIndex(a => a.job === o.job);
if (index !== -1) {
acc[index].workersInfo.push({ id: o.id, name: o.name });
} else {
acc.push({
job: o.job,
workersInfo: [{ id: o.id, name: o.name }],
});
}
return acc;
}, []);
console.log(output);
Would something like this work ?
const groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
console.log(groupBy(['one', 'two', 'three'], 'length'));
// => {3: ["one", "two"], 5: ["three"]}```
It would be more efficient and comprehensible if instead of having a structure like Array<{job: string, workForce: Array}>, you had something like {[job: string]: Array}
var data = [
{ id: 1, name: 'Alex', job: 'IT' },
{ id: 2, name: 'Pavel', job: 'IT' },
{ id: 3, name: 'Joe', job: 'IT' },
{ id: 4, name: 'Josh', job: 'IT' },
{ id: 5, name: 'Max', job: 'teacher' },
{ id: 6, name: 'Sam', job: 'teacher' }
];
var jobs = data.reduce(function (result, person) {
var jobList = result[person.job];
if (!jobList) {
jobList = [];
result[person.job] = jobList;
}
jobList.push(person);
return result;
}, {});
console.log(jobs);

JS How to get matching id between 2 array object

How do I get 2 matching id between 2 array object using javascript?
// Array 1
const array1 = [
{id: 1, name: 'milla'},
{id: 2, name: 'alice'}
]
// Array 2
const array2 = [
{id: 3, name: 'bobba', height: '170cm', age: 22},
{id: 2, name: 'alice', height: '169cm', age: 21},
{id: 1, name: 'milla', height: '171cm', age: 24},
{id: 4, name: 'ricky', height: '168cm', age: 32},
]
the expected output is to returned array of object of Array2 that mached with id's on array1
// expected result
[
{id: 2, name: 'alice', height: '169cm', age: 21},
{id: 1, name: 'milla', height: '171cm', age: 24},
]
You could filter and look if the same id exists.
const
array1 = [{ id: 1, name: 'milla' }, { id: 2, name: 'alice' }],
array2 = [{ id: 3, name: 'bobba', height: '170cm', age: 22 }, { id: 2, name: 'alice', height: '169cm', age: 21 }, { id: 1, name: 'milla', height: '171cm', age: 24 }, { id: 4, name: 'ricky', height: '168cm', age: 32 }],
hash = array1.reduce((r, { id }) => (r[id] = true, r), {}),
filtered = array2.filter(({ id }) => hash[id]);
console.log(filtered);
The most efficient way to do this is to generate a map of the IDs in array1 and then filter array2 against those IDs, like so:
let array1 = [{ id: 1, name: 'milla' }, { id: 2, name: 'alice' }];
let array2 = [{ id: 3, name: 'bobba', height: '170cm', age: 22 }, { id: 2, name: 'alice', height: '169cm', age: 21 }, { id: 1, name: 'milla', height: '171cm', age: 24 }, { id: 4, name: 'ricky', height: '168cm', age: 32 }];
let idMap = array1.reduce((res, curr) => (res[curr.id] = true, res), {});
let filtered = array2.filter((item) => idMap[item.id]);
console.log(filtered)
Honestly, this is basic JS, but anyway, here's the solution:
const array1 = [
{id: 1, name: 'milla'},
{id: 2, name: 'alice'}
]
// Array 2
const array2 = [
{id: 3, name: 'bobba', height: '170cm', age: 22},
{id: 2, name: 'alice', height: '169cm', age: 21},
{id: 1, name: 'milla', height: '171cm', age: 24},
{id: 4, name: 'ricky', height: '168cm', age: 32},
]
const map = array1.reduce((a, c) => ({ ...a, [c.id]: true }), {});
const array3 = array2.filter(item => map[item.id]);
console.log(array3);

array of object into array of object but different (javascript)

Using javascript, I have this array:
people = [{name: carlo, lastname: Garcia, age: 28},
{name: maria, lastname: pia, age: 20},
{name: elly, lastname: martinez, age: 25}]
I would like to transform it into:
arrayList = [{data: {name: carlo, lastname: garcia, age: 28}, checked: false},
{data: {name: carlo, lastname: garcia, age: 28}, checked: false},
{data: {name: carlo, lastname: garcia, age: 28}, checked: false}]
How can I do it?
You want to use Array.prototype.map
var people = [{ name: "carlo", lastname: "Garcia", age: 28 }, { name: "maria", lastname: "pia", age: 20 }, { name: "elly", lastname: "martinez", age: 25 }]
var arrayList = people.map(person => ({
data: person,
checked: false,
}))
console.log(arrayList);
Just use map(). Return an object with data and checked fields.
Where:
data is set to each person
checked is set to false
people = [{name: 'carlo', lastname: 'Garcia', age: 28},{name: 'maria', lastname: 'pia', age: 20},{name: 'elly', lastname: 'martinez', age: 25}]
arrayList = people.map(p => ({ data: p, checked: false }))
console.log(arrayList)

lodash javascript array of duplicates that match multiple parameters

I have an array, to simplify lets say persons with first, last, and age. I want to make a new array of all persons that have the same first name, same last name and same age. For example my starting array:
[
{id: 1, first: 'fred', last: 'smith', age: 21},
{id: 2, first: 'fred', last: 'smith', age: 21},
{id: 3, first: 'tom', last: 'smith', age: 21},
{id: 4, first: 'fred', last: 'smith', age: 32}
]
I would like to return the duplicates that match first/last/age:
[
{id: 1, first: 'fred', last: 'smith', age: 21},
{id: 2, first: 'fred', last: 'smith', age: 21}
]
I'm struggling with _.uniq to figure out how to do this, any help is appreciated.
You can make use of _.groupBy() to group values, make sure that it is grouped by values that you determine to be the criteria for a duplicate. You can then _.filter() each grouped values by the lengths of the arrays they accumulated and then _.flatten() it to obtain the final array.
var data = [
{id: 1, first: 'fred', last: 'smith', age: 21},
{id: 2, first: 'fred', last: 'smith', age: 21},
{id: 3, first: 'tom', last: 'smith', age: 21},
{id: 4, first: 'fred', last: 'smith', age: 32}
];
var result = _(data)
.groupBy(i => _(i).pick('first', 'last', 'age').values().value())
.filter(i => i.length > 1)
.flatten()
.value();
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>

Categories

Resources