how to transform array of object using reduce of map? - javascript

I am trying to transform array of object to different format.I also take reference from this url
Group js objects by multiple properties
But not able to solve the problem
I have a input array of object which have class and sections I need to transform or filter student in different format on basis of class and section.
here is my code
https://jsbin.com/nidudisuza/edit?js,output
let expectedout = [
{
class: 1,
sections: [{
"section": "B",
students: [ {
"name": "Test",
"class": 1,
"gender": "M",
"section": "B",
"rollNumber": "123111",
"sports": [
"Badminton",
"Chess"
],
"age": 7
}]
}]
},
{
class: 3,
sections: [{
"section": "B",
students: [{
"name": "Rahul",
"class": 3,
"gender": "M",
"section": "B",
"rollNumber": "1231",
"sports": [
"Badminton",
"Chess"
],
"age": 7
}]
}]
},
{
class: 5,
sections: [{
"section": "C",
students: [
{
"name": "Rajat",
"class": 5,
"gender": "M",
"section": "C",
"rollNumber": "123122",
"sports": [
"Chess"
],
"age": 9
}
]
}]
}
]
const input = [{
"name": "Rahul",
"class": 3,
"gender": "M",
"section": "B",
"rollNumber": "1231",
"sports": [
"Badminton",
"Chess"
],
"age": 7
},
{
"name": "Rajat",
"class": 5,
"gender": "M",
"section": "C",
"rollNumber": "123122",
"sports": [
"Chess"
],
"age": 9
},
{
"name": "Test",
"class": 1,
"gender": "M",
"section": "B",
"rollNumber": "123111",
"sports": [
"Badminton",
"Chess"
],
"age": 7
},
]
function abc() {
// let output =
// data.map((i) => {
// let obj = {};
// obj.class = i.class;
// obj.sections = [];
// obj.sections.push({
// section:obj.section,
// students:[obj]
// })
// return obj;
// })
let output =input.reduce((acc,i)=>{
let cls = i.class;
const found = acc.some(el => el.class === cls);
let obj = {
section:i.section,
students:[]
}
found.sections.students.push[i]
},[])
return output
}
console.log(abc())
}

I'd go for a 2 step process:
Reorganize the values to be mapped by an index (both for class and sections)
Then flatten out everything in arrays; depending on what you're doing having a dictionary could also be convenient.
Below you can find the function that makes the dictionary, in the snippet there is also the second step that transforms the dictionary values in arrays.
function abc() {
let output = input.reduce((ac, x) => {
let keyCl = x.class
let keySec = x.section
let orgClass = ac[keyCl]
let sections = orgClass && orgClass.sections || {}
let oldSec = sections && sections[keySec]
let sectionBase = oldSec || {
section: keySec,
students: []
}
sectionBase.students = [...(oldSec ? .students || []), x]
return {
...ac,
// we organize classes to be indexed in an obj,
// we can flat this out later
[keyCl]: {
class: keyCl,
sections: {
...sections,
// like for classes we organize sections by key
[keySec]: sectionBase
}
}
}
}, {})
return output
}
let expectedout = [{
class: 1,
sections: [{
"section": "B",
students: [{
"name": "Test",
"class": 1,
"gender": "M",
"section": "B",
"rollNumber": "123111",
"sports": [
"Badminton",
"Chess"
],
"age": 7
}]
}]
},
{
class: 3,
sections: [{
"section": "B",
students: [{
"name": "Rahul",
"class": 3,
"gender": "M",
"section": "B",
"rollNumber": "1231",
"sports": [
"Badminton",
"Chess"
],
"age": 7
}]
}]
},
{
class: 5,
sections: [{
"section": "C",
students: [
{
"name": "Rajat",
"class": 5,
"gender": "M",
"section": "C",
"rollNumber": "123122",
"sports": [
"Chess"
],
"age": 9
}
]
}]
}
]
const input = [{
"name": "Rahul",
"class": 3,
"gender": "M",
"section": "B",
"rollNumber": "1231",
"sports": [
"Badminton",
"Chess"
],
"age": 7
},
{
"name": "Rajat",
"class": 5,
"gender": "M",
"section": "C",
"rollNumber": "123122",
"sports": [
"Chess"
],
"age": 9
},
{
"name": "Test",
"class": 1,
"gender": "M",
"section": "B",
"rollNumber": "123111",
"sports": [
"Badminton",
"Chess"
],
"age": 7
},
]
function abc() {
let output = input.reduce((ac, x) => {
let keyCl = x.class
let keySec = x.section
let orgClass = ac[keyCl]
let sections = orgClass && orgClass.sections || {}
let oldSec = sections && sections[keySec]
let sectionBase = oldSec || {
section: keySec,
students: []
}
sectionBase.students = [...(oldSec && oldSec.students || []), x]
return {
...ac,
// we organize classes to be indexed in an obj,
// we can flat this out later
[keyCl]: {
class: keyCl,
sections: {
...sections,
// like for classes we organize sections by key
[keySec]: sectionBase
}
}
}
}, {})
return output
}
let res = abc()
console.log('with keys', res)
let onlyValues = Object.values(res).map(x => ({ ...x,
sections: Object.values(x.sections)
}))
console.log('only values', onlyValues)

Using Array#reduce to build an Object with the collected data. Foreach object look in the accumulated object if there exists an prperty for this class. If not create one and add to this the groundstructure for this class.
Afterwards add in both cases to the students array a new entry for this student.
After creating by this the object use Object#entries to take only the values of the object to get the ished array.
function modify(data) {
let res= Object.values(data.reduce((acc, cur) => {
if (!acc[cur.class]) {
acc[cur.class] = {
class: cur.class,
sections: [{
"section": cur.section,
students: []
}]
};
}
acc[cur.class].sections[0].students.push(cur);
return acc;
},{}));
return res;
}
const data = [{
"name": "Rahul",
"class": 3,
"gender": "M",
"section": "B",
"rollNumber": "1231",
"sports": [
"Badminton",
"Chess"
],
"age": 7
},
{
"name": "Rajat",
"class": 5,
"gender": "M",
"section": "C",
"rollNumber": "123122",
"sports": [
"Chess"
],
"age": 9
},
{
"name": "Test",
"class": 1,
"gender": "M",
"section": "B",
"rollNumber": "123111",
"sports": [
"Badminton",
"Chess"
],
"age": 7
},
]
console.log(modify(data));

Related

Assigning a grouped index within a javascript array

How would I assign an index to each object within a group in an array using javascript. So starting at zero and counting up inside each group, ordered by the group then the id.
Starting with this
let data = [
{ "id": "AB", "name": "Fred", "group": 1},
{ "id": "BC", "name": "Jane", "group": 2 },
{ "id": "CD", "name": "Mary", "group": 1 },
{ "id": "DE", "name": "Bob", "group": 2 },
{ "id": "EF", "name": "Chris", "group": 1 },
{ "id": "FG", "name": "Steve", "group": 2 },
{ "id": "GH", "name": "Jim", "group": 2 }
]
But adding the groupIndex field for each object.
dataGrouped = [
{ "id": "DE", "name": "Bob", "group": 2, "groupIndex": 1 },
{ "id": "EF", "name": "Chris", "group": 1, "groupIndex": 2 },
{ "id": "BC", "name": "Jane", "group": 2, "groupIndex": 0 },
{ "id": "FG", "name": "Steve", "group": 2, "groupIndex": 2 },
{ "id": "AB", "name": "Fred", "group": 1, "groupIndex": 0},
{ "id": "CD", "name": "Mary", "group": 1, "groupIndex": 1 },
{ "id": "GH", "name": "Jim", "group": 2, "groupIndex": 3 }
]
You could take an object for the indices.
const
indices = {},
data = [{ id: "AB", name: "Fred", group: 1 }, { id: "BC", name: "Jane", group: 2 }, { id: "CD", name: "Mary", group: 1 }, { id: "DE", name: "Bob", group: 2 }, { id: "EF", name: "Chris", group: 1 }, { id: "FG", name: "Steve", group: 2 }, { id: "GH", name: "Jim", group: 2 }],
result = data.map(o => {
indices[o.group] ??= 0;
return { ...o, groupIndex: indices[o.group]++ };
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Presented below is one possible way to achieve the desired objective (viz, assigning group index to array elements). This solution does not address: "ordered by the group then the id."
Code Snippet
// method to assign group-index
// the resulting array may get ordered based on group & group-index (ascending)
const assignGroupIndex = arr => (
Object.values(
arr?.reduce(
(acc, { group, ...rest }) => {
if (!(group in acc)) acc[group] = [];
acc[group].push({
group, ...rest, groupIndex: acc[group].length,
});
return acc;
},
{}
)
).flat()
);
/*
// method to assign group-index for each elt in array
const assignGroupIndex = arr => ( // arg "arr" is the input array
// extract the values from the intermediate result object generated below
Object.values(
// use ".reduce()" to iterate the array and generate an intermediate result
arr?.reduce(
// "acc" is the accumulator, destructure to access "group" & other props
(acc, { group, ...rest }) => {
// if "group" not already in accumulator, set the value as empty array
if (!(group in acc)) acc[group] = [];
// push to the array a new object with "groupIndex" as current length
acc[group].push({
group, ...rest, groupIndex: acc[group].length,
});
// always return the accumulator for each iteration of ".reduce()"
return acc;
},
{} // "acc" - the accumulator is initialized as empty object
)
).flat() // use ".flat()" to remove nested arrays from Object.values()
);
*/
let data = [
{ "id": "AB", "name": "Fred", "group": 1},
{ "id": "BC", "name": "Jane", "group": 2 },
{ "id": "CD", "name": "Mary", "group": 1 },
{ "id": "DE", "name": "Bob", "group": 2 },
{ "id": "EF", "name": "Chris", "group": 1 },
{ "id": "FG", "name": "Steve", "group": 2 },
{ "id": "GH", "name": "Jim", "group": 2 }
];
console.log(
'assigned group-index to array:\n',
assignGroupIndex(data)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Inline comments added to the snippet above.
let data = [
{ "id": "AB", "name": "Fred", "group": 1},
{ "id": "BC", "name": "Jane", "group": 2 },
{ "id": "CD", "name": "Mary", "group": 1 },
{ "id": "DE", "name": "Bob", "group": 2 },
{ "id": "EF", "name": "Chris", "group": 1 },
{ "id": "FG", "name": "Steve", "group": 2 },
{ "id": "GH", "name": "Jim", "group": 2 }
];
let groupCounts = {};
let dataGrouped = data.map(i=>({
...i,
groupIndex: groupCounts[i.group] = ++groupCounts[i.group] || 0
})).sort((a,b)=>a.group-b.group || a.id.localeCompare(b.id));
console.log(dataGrouped);

Need a way to randomly pick a value from an array of objects without traversing the parent

I am still fairly new to JavaScript and need help with a task I am trying to accomplish.
I have an array of objects like this:
const data =
{
"Total_packages": {
"package1": {
"tags": [
"kj21",
"j1",
"sj2",
"z1"
],
"expectedResponse": [
{
"firstName": "Name",
"lastName": "lastName",
"purchase": [
{
"title": "title",
"category": [
"a",
"b",
"c"
]
}
]
}
]
},
"package2": {
"tags": [
"s2",
"dsd3",
"mhg",
"sz7"
],
"expectedResponse": [
{
"firstName": "Name1",
"lastName": "lastName1",
"purchase": [
{
"title": "title1",
"category": [
"a1",
"b1",
"c1"
]
}
]
}
]
},
"package3": {
"tags": [
"s21",
"dsd31",
"mhg1",
"sz71"
],
"expectedResponse": [
{
"firstName": "Name2",
"lastName": "lastName2",
"purchase": [
{
"title": "title2",
"category": [
"a2",
"b2",
"c2"
]
}
]
}
]
},
"package4": {
"tags": [
"s22",
"dsd32",
"mhg2",
"sz72"
],
"expectedResponse": [
{
"firstName": "Name3",
"lastName": "lastName3",
"purchase": [
{
"title": "title3",
"category": [
"a3",
"b3",
"c3"
]
}
]
}
]
},
"package5": {
"tags": [
"s22",
"dsd32",
"mhg2",
"sz72"
],
"expectedResponse": [
{
"firstName": "Name4",
"lastName": "lastName4",
"purchase": [
{
"title": "title4",
"category": [
"a4",
"b4",
"c4"
]
}
]
}
]
}
}
}
var arrRand = genNum(data, 3);
console.log(arrRand);
function genNum(data, loop='') {
var list = [];
var arrayOfTags = Object.entries(data.Total_packages).reduce((acc, [k, v]) => {
if (v.tags) acc = acc.concat(v.tags.map(t => ({tag: t, response: v.expectedResponse})));
return acc;
}, []);
for (var i = 0; i < loop; i++){
var randomIndex = Math.floor(Math.random() * arrayOfTags.length);
var randomTag = arrayOfTags[randomIndex];
list.push(randomTag);
}
return list;
}
I then access the values I need by doing something like arrRand[0].tag and arrRand[0].response.
Often times I get duplicate responses from the method such as following and it becomes problematic:
[
{
"tag": "s22",
"response": [
{
"firstName": "Name4",
"lastName": "lastName4",
"purchase": [
{
"title": "title4",
"category": [
"a4",
"b4",
"c4"
]
}
]
}
]
},
{
"tag": "dsd31",
"response": [
{
"firstName": "Name2",
"lastName": "lastName2",
"purchase": [
{
"title": "title2",
"category": [
"a2",
"b2",
"c2"
]
}
]
}
]
},
{
"tag": "dsd31",
"response": [
{
"firstName": "Name2",
"lastName": "lastName2",
"purchase": [
{
"title": "title2",
"category": [
"a2",
"b2",
"c2"
]
}
]
}
]
}
]
My goal is to send API requests with a random "tags" value from above and then match the response I get from the call to the expectedResponse part of the data.
My initial thought was to do something like:
data.Total_packages.tags[Math.floor(Math.random() * data.Total_packages.tags.length)];
However, I can't call on "tags" without traversing through its parent i.e "package1" or "package2", so then it won't be random anymore.
I know there is probably a very simple way to do it that I am not getting. Any advice would be appreciated.
You could build an array from the various tags elements, and use that to do random things.
const data =
{
"Total_packages": {
"package1": {
"tags": [
"kj21",
"j1",
"sj2",
"z1"
],
"expectedResponse": [
{
"firstName": "Name",
"lastName": "lastName",
"purchase": [
{
"title": "title",
"category": [
"a",
"b",
"c"
]
}
]
}
]
},
"package2": {
"tags": [
"s2",
"dsd3",
"mhg",
"sz7"
],
"expectedResponse": [
{
"firstName": "Name1",
"lastName": "lastName1",
"purchase": [
{
"title": "title1",
"category": [
"a1",
"b1",
"c1"
]
}
]
}
]
}
}
}
const arrayOfTags = Object.entries(data.Total_packages).reduce((acc, [k, v]) => {
if (v.tags) acc = acc.concat(v.tags.map(t => ({tag: t, response: v.expectedResponse})));
return acc;
}, []);
const randomIndex = Math.floor(Math.random() * arrayOfTags.length);
const randomTag = arrayOfTags[randomIndex];
console.log(randomTag.tag, randomTag.response);
You will need to mine the tags, put them together into an array and randomize the index, finally get the value there. The solution below assumes that your tags are all arrays inside data.Total_packages[whateverpackage]
const data =
{
"Total_packages": {
"package1": {
"tags": [
"kj21",
"j1",
"sj2",
"z1"
],
"expectedResponse": [
{
"firstName": "Name",
"lastName": "lastName",
"purchase": [
{
"title": "title",
"category": [
"a",
"b",
"c"
]
}
]
}
]
},
"package2": {
"tags": [
"s2",
"dsd3",
"mhg",
"sz7"
],
"expectedResponse": [
{
"firstName": "Name1",
"lastName": "lastName1",
"purchase": [
{
"title": "title1",
"category": [
"a1",
"b1",
"c1"
]
}
]
}
]
}
}
}
let tags = [];
for (let key in data.Total_packages) {
if (data.Total_packages[key].tags) tags = tags.concat(data.Total_packages[key].tags);
}
console.log(tags[parseInt(tags.length * Math.random())]);
EDIT
In the comment section you have mentioned that you have duplicates of the form of
[
{
"tag": "s22",
"response": [
{
"firstName": "Name4",
"lastName": "lastName4",
"purchase": [
{
"title": "title4",
"category": [
"a4",
"b4",
"c4"
]
}
]
}
]
},
{
"tag": "dsd31",
"response": [
{
"firstName": "Name2",
"lastName": "lastName2",
"purchase": [
{
"title": "title2",
"category": [
"a2",
"b2",
"c2"
]
}
]
}
]
},
{
"tag": "dsd31",
"response": [
{
"firstName": "Name2",
"lastName": "lastName2",
"purchase": [
{
"title": "title2",
"category": [
"a2",
"b2",
"c2"
]
}
]
}
]
}
]
This is how you can get rid of duplicates:
let input = [
{
"tag": "s22",
"response": [
{
"firstName": "Name4",
"lastName": "lastName4",
"purchase": [
{
"title": "title4",
"category": [
"a4",
"b4",
"c4"
]
}
]
}
]
},
{
"tag": "dsd31",
"response": [
{
"firstName": "Name2",
"lastName": "lastName2",
"purchase": [
{
"title": "title2",
"category": [
"a2",
"b2",
"c2"
]
}
]
}
]
},
{
"tag": "dsd31",
"response": [
{
"firstName": "Name2",
"lastName": "lastName2",
"purchase": [
{
"title": "title2",
"category": [
"a2",
"b2",
"c2"
]
}
]
}
]
}
];
let output = input.filter((item, index) => {
return input.filter((item2, index2) => {
return ((item.tag === item2.tag) && (index2 < index));
}).length === 0;
});
console.log(output);
We search for items who have no matches on earlier indexes.
i saved all tags in a separate array and kept the ref of expectedResponse in the block. then it's a matter or randomly selecting one tag index and matching with the block expectedResponse index. probably needs some adjustment to the random/length but i hope it puts you in the right direction.
var tags = []
var block = Object.values(data.Total_packages).flat()
block.forEach(item => tags = [...tags, ...item.tags])
var index = tags[parseInt(tags.length * Math.random())]
console.log(block[Math.floor(tags.indexOf(index) / 4)].expectedResponse)

Creating a new array from the parents of array child element

I have the following array
{
"id": "111",
"name": "1111",
"children": [
{
"id": "22222",
"name": "2222",
"children": [
{
"id": "AAAA",
"name": "AAAA",
"children": [
{
"id": "DDD",
"name": "DDD"
},
{
"id": "EEE",
"name": "EEE"
}
]
},
{
"id": "BBBB",
"name": "BBB",
"children": [
{
"id": "FFF",
"name": "FFF"
},
{
"id": "GGG",
"name": "GGG",
"children": [
{
"id": "7777",
"name": "7777"
},
{
"id": "8888",
"name": "8888"
}
]
}
]
}
]
}
]
}
And I would like to create an array with the parents of a child by its ID.
So for example if I wanted to get the path to the child with ID "FFF", then the array would look like something like this:
["1111", "2222", "BBB", "FFF"]
How could I go about doing that?
You could take an iterative and recursive approach.
function getItems({ children, ...object }, key, value) {
var temp;
if (object[key] === value) return [object];
if (children) children.some(o => temp = getItems(o, key, value));
return temp && [object, ...temp];
}
var data = { id: "111", name: "1111", children: [{ id: "22222", name: "2222", children: [{ id: "AAAA", name: "AAAA", children: [{ id: "DDD", name: "DDD" }, { id: "EEE", name: "EEE" }] }, { id: "BBBB", name: "BBB", children: [{ id: "FFF", name: "FFF" }, { id: "GGG", name: "GGG", children: [{ id: "7777", name: "7777" }, { id: "8888", name: "8888" }] }] }] }] };
console.log(getItems(data, 'id', 'FFF'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could implement a recursive search to find all paths and return the correct one when you reach the desired name-value pair.
const isObject = (obj) => obj === Object(obj);
let data = loadData();
let expected = [ '1111', '2222', 'BBB', 'FFF' ];
let actual = findPath(data, 'name', 'FFF');
console.log(JSON.stringify(expected) === JSON.stringify(actual));
function findPath(data, key, value, includeIndicies=false) {
let opts = { found : null, includeIndicies : includeIndicies };
findPathInternal(data, key, value, opts, []);
return opts.found;
}
function findPathInternal(node, key, val, opts, path) {
if (Array.isArray(node)) {
for (let i = 0; i < node.length; i++) {
findPathInternal(node[i], key, val, opts, opts.includeIndicies ? path.concat(i) : path);
}
} else if (isObject(node)) {
if (node[key] === val) {
opts.found = path.concat(val); return; // Exit
} else {
let keys = Object.keys(node);
for (let i = 0; i < keys.length; i++) {
findPathInternal(node[keys[i]], key, val, opts, path.concat(node[key]));
}
}
}
};
function loadData() {
return {
"id": "111",
"name": "1111",
"children": [{
"id": "22222",
"name": "2222",
"children": [{
"id": "AAAA",
"name": "AAAA",
"children": [{
"id": "DDD",
"name": "DDD"
},
{
"id": "EEE",
"name": "EEE"
}
]
},
{
"id": "BBBB",
"name": "BBB",
"children": [{
"id": "FFF",
"name": "FFF"
},
{
"id": "GGG",
"name": "GGG",
"children": [{
"id": "7777",
"name": "7777"
},
{
"id": "8888",
"name": "8888"
}
]
}
]
}
]
}]
};
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

How to flatten and merge nested array from each of child array

So i have this data:
let data = [
{
"purchase_id": 1,
"product": [
{
"name": "A",
"id": 1,
"transactions": [
{
"price": 5,
"qty": 2
},
{
"price": 10,
"qty": 2
}
]
},
{
"name": "B",
"id": 2,
"transactions": [
{
"price": 3,
"qty": 4
}
]
}
]
},
{
"purchase_id": 2,
"product": [
{
"name": "C",
"id": 3,
"transactions": [
{
"price": 5,
"qty": 2
}
]
},
{
"name": "D",
"id": 4,
"transactions": [
{
"price": 3,
"qty": 4
}
]
}
]
}
]
And i want to flatten array from each data.product.transactions data:
"transactions": [
{
"price",
"qty"
}
]
Expected output is:
[
{
"purchase_id": 1,
"name": "A",
"id": 1,
"price": 5,
"qty": 2
},
{
"purchase_id": 1,
"name": "A",
"id": 1,
"price": 10,
"qty": 2
},
{
"purchase_id": 1,
"name": "B",
"id": 2,
"price": 3,
"qty": 4
},
{
"purchase_id": 2,
"name": "C",
"id": 3,
"price": 5,
"qty": 2
},
{
"purchase_id": 2,
"name": "D",
"id": 4,
"price": 3,
"qty": 4
},
]
I have tried to use object assign, reduce but my code doesn't work. Thank you
Use nested Array.map() to create the objects, and spread into Array.concat() to flatten the sub-arrays at each level:
const data = [{"purchase_id":1,"product":[{"name":"A","id":1,"transactions":[{"price":5,"qty":2},{"price":10,"qty":2}]},{"name":"B","id":2,"transactions":[{"price":3,"qty":4}]}]},{"purchase_id":2,"product":[{"name":"C","id":3,"transactions":[{"price":5,"qty":2}]},{"name":"D","id":4,"transactions":[{"price":3,"qty":4}]}]}];
const result = [].concat(...data.map(({ purchase_id, product }) =>
[].concat(...product.map(({ name, id, transactions }) =>
transactions.map((o) => ({
purchase_id,
name,
id,
...o
})
)))));
console.log(result);
If you want to avoid the temp sub-arrays, and the flattering, use nested Array.forEach() calls, and push the created objects to a predefined array:
const data = [{"purchase_id":1,"product":[{"name":"A","id":1,"transactions":[{"price":5,"qty":2},{"price":10,"qty":2}]},{"name":"B","id":2,"transactions":[{"price":3,"qty":4}]}]},{"purchase_id":2,"product":[{"name":"C","id":3,"transactions":[{"price":5,"qty":2}]},{"name":"D","id":4,"transactions":[{"price":3,"qty":4}]}]}];
const result = [];
data.forEach(({ purchase_id, product }) =>
product.forEach(({ name, id, transactions }) =>
transactions.forEach((o) => result.push({
purchase_id,
name,
id,
...o
})
)));
console.log(result);
var arr = [];
data.forEach(x => {
x.product.forEach(y => {
y.transactions.forEach(z => {
z["name"] = y.name;
z["id"] = y.id;
z["purchase_id"] = x.purchase_id;
arr.push(z);
});
})
});
console.log(arr);

How to reduce and filter arrays in javascript?

So I want to filter my array as followed:
Lets say my array1 = ['c', 'd']
My data array =
[{
"userid": "a",
"age": 19,
"name": "john"
}, {
"userid": "c",
"age": 119,
"name": "joy"
}, {
"userid": "d",
"age": 119,
"name": "jesse"
}]
I want to filter out my data array so that only those objects in data array are there whose userid values are present in array1.
Expected result:
new data array = [{
"userid": "c",
"age": 119,
"name": "joy"
}, {
"userid": "d",
"age": 119,
"name": "jesse"
}]
To make you understand better, adding Tushar's solution without lambda expression,
newDataArray = dataArray.filter(function(item) {return array1.includes(item.userid)})
In ES5:
var newDataArray = dataArray.filter(function (item) {
return array1.indexOf(item.userid) !== -1;
});
var a1 = [
{
"userid": "a",
"age": 19,
"name": "john"
},
{
"userid": "c",
"age": 119,
"name": "joy"
},
{
"userid": "d",
"age": 119,
"name": "jesse"
}
];
var a2 = ['c','d'];
var newObj = [];
a1.filter(function(object,index){
var x = object.userid;
a2.filter(function(userId){
if(x==userId){
newObj[index-1] = object;
}
});
});
console.log(JSON.stringify(newObj));

Categories

Resources