I am working on a Javascript array where I need to loop the 2nd array in the main array and get the total sum of a value of a particular field. below is what my JSON looks like. here I need to loop Array and get the sum of ps_lessons.lesson_length_minutes I need the O/P as 118 (20 + 22 + 33 + 43)
[
{
"sort_id": 1,
"category": "Introduction",
"ps_lessons": [
{
"id": "48ca672b-aaca-473c-b54b-3cf699da848b",
"sort_id": 1,
"lesson_title": "Welcome to the course",
"lesson_length_minutes": 20
},
{
"id": "3f0f5715-a442-4262-ad32-6fb653df62c2",
"sort_id": 2,
"lesson_title": "What is React JS?",
"lesson_length_minutes": 22
}
]
},
{
"sort_id": 2,
"category": "Fundamentals",
"ps_lessons": [
{
"id": "e28abd67-29a4-4bc9-a415-fb5db0aabfa9",
"sort_id": 4,
"lesson_title": "Fundamentals of React JS",
"lesson_length_minutes": 33
},
{
"id": "1d9668da-94e6-4085-bd89-176cc4e8e62d",
"sort_id": 3,
"lesson_title": "Fundamentals of JSX",
"lesson_length_minutes": 43
}
]
}
]
I tried something like the below by using the array method map 2 times but it's not working. can anyone suggest how to do this?
const extract_mins_and_sum = (result) => {
console.log('result', result);
result.map((single_row) =>
let sum = 0;
single_row.ps_lessons.map((single_row_lesson) =>
( console.log(single_row_lesson.lesson_length_minutes);
sum += single_row_lesson.lesson_length_minutes)
)
);
};
Thanks
Venk
You can try map, flat and reduce.
const extract_mins_and_sum = (result) => {
return result.map(x => x.ps_lessons.map(y => y.lesson_length_minutes)).flat().reduce((a, b) => a + b, 0)
};
The straightforward way is to loop through each element of the big array and get the sum by using a reduce function on each ps_lessons array.
const extract_mins_and_sum = (result) => {
let sum = 0;
result.forEach((elem) => {
sum += elem.ps_lessons.reduce((acc, val) => acc + val.lesson_length_minutes, 0);
});
return sum;
}
Map is generally used to map an array to another array, but preserving metadata like array length, order etc.
Reduce is generally used to, well, reduce an array to a single value, based on whatever logic you use in the callback function. On this example, reduce is used to transform an array into a sum of some numeric fields.
You could use a solution using map and reduce extracting the value to an external variable like so:
const data = [
{
sort_id: 1,
category: "Introduction",
ps_lessons: [
{
id: "48ca672b-aaca-473c-b54b-3cf699da848b",
sort_id: 1,
lesson_title: "Welcome to the course",
lesson_length_minutes: 20,
},
{
id: "3f0f5715-a442-4262-ad32-6fb653df62c2",
sort_id: 2,
lesson_title: "What is React JS?",
lesson_length_minutes: 22,
},
],
},
{
sort_id: 2,
category: "Fundamentals",
ps_lessons: [
{
id: "e28abd67-29a4-4bc9-a415-fb5db0aabfa9",
sort_id: 4,
lesson_title: "Fundamentals of React JS",
lesson_length_minutes: 33,
},
{
id: "1d9668da-94e6-4085-bd89-176cc4e8e62d",
sort_id: 3,
lesson_title: "Fundamentals of JSX",
lesson_length_minutes: 43,
},
],
},
];
const sumMinutes = (lessons) => {
return lessons.reduce((acc, ps) => {
return (acc + (ps.ps_lessons ? sumMinutes(ps.ps_lessons): ps.lesson_length_minutes));
}, 0);
};
console.log(sumMinutes(data))
You can use reduce function to solve this
const data = [
{
sort_id: 1,
category: "Introduction",
ps_lessons: [
{
id: "48ca672b-aaca-473c-b54b-3cf699da848b",
sort_id: 1,
lesson_title: "Welcome to the course",
lesson_length_minutes: 20,
},
{
id: "3f0f5715-a442-4262-ad32-6fb653df62c2",
sort_id: 2,
lesson_title: "What is React JS?",
lesson_length_minutes: 22,
},
],
},
{
sort_id: 2,
category: "Fundamentals",
ps_lessons: [
{
id: "e28abd67-29a4-4bc9-a415-fb5db0aabfa9",
sort_id: 4,
lesson_title: "Fundamentals of React JS",
lesson_length_minutes: 33,
},
{
id: "1d9668da-94e6-4085-bd89-176cc4e8e62d",
sort_id: 3,
lesson_title: "Fundamentals of JSX",
lesson_length_minutes: 43,
},
],
},
];
const sumMinutes = (lessons) => {
return lessons.reduce((acc, ps) => {
return (acc + (ps.ps_lessons ? sumMinutes(ps.ps_lessons): ps.lesson_length_minutes));
}, 0);
};
console.log(sumMinutes(data))
Related
I have an array of arrays, which contain objects, would like to get the value of a certain key and return it as a big array, have tried a nested map but it returns multiple array's rather than a single array.
const items = [
{
id: 1,
sub_items: [
{
id: 1
},
{
id: 2
},
{
id: 3
}
]
},
{
id: 2,
sub_items: [
{
id: 4
},
{
id: 5
},
{
id: 6
}
]
}
]
const subItemIDs = items.map( (item) =>
item.sub_items.map( (subItem) => subItem.id )
)
console.log(subItemIDs);
Expected output
[1, 2, 3, 4, 5, 6]
Actual output
[ [1,2,3], [4,5,6] ]
You can use arrays.flat(). I can provide more specific code once output is mentioned in the question
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]
You could take Array#flatMap to get a flat array from nested arrays.
const
items = [{ id: 1, sub_items: [{ id: 1 }, { id: 2 }, { id: 3 }] }, { id: 2, sub_items: [{ id: 4 }, { id: 5 }, { id: 6 }] }],
subItemIDs = items.flatMap(({ sub_items }) => sub_items.map(({ id }) => id));
console.log(subItemIDs);
Achieved this with:
const items = [
{
id: 1,
sub_items: [
{
id: 1
},
{
id: 2
},
{
id: 3
}
]
},
{
id: 2,
sub_items: [
{
id: 4
},
{
id: 5
},
{
id: 6
}
]
}
]
const subItemIDs = [].concat(...items.map( (item) =>
item.sub_items.map( (subItem) => subItem.id )
))
console.log(subItemIDs);
Sometimes, the obvious is the easiest:
Given a data structure that looks like this
const items = [
{ id: 1, sub_items: [ { id: 1 }, { id: 2 }, { id: 3 }, ] },
{ id: 2, sub_items: [ { id: 4 }, { id: 5 }, { id: 6 }, ] },
];
A trivial function like this
function extract_item_ids( items ) {
const ids = [];
for ( const item of items ) {
for ( const {id} of sub_items ) {
ids.push(id);
}
}
return ids;
}
should do the trick. If you want to collect the ids from a tree of any depth, it's just as easy:
function extract_item_ids( items ) {
const ids = [];
const pending = items;
while ( pending.length > 0 ) {
const item = pending.pop();
ids.push(item.id);
pending.push(...( item.sub_items || [] ) );
}
return ids;
}
And collecting the set of discrete item IDs is no more difficult:
If you want to collect the ids from a tree of any depth, it's just as easy:
function extract_item_ids( items ) {
const ids = new Set();
const pending = [...items];
while ( pending.length > 0 ) {
const item = pending.pop();
ids.add(item.id);
pending.push(...( item.sub_items || [] ) );
}
return Array.from(ids);
}
As is the case with most things JavaScript, you have several options. Some are more efficient than others, others have a certain stylistic purity, others might better speak to your fancy. Here are a few:
Array.flat
With array flat you can take your original code and have the JS Engine flatten the array down to a one-dimensional array. Simply append .flat() onto the end of your map.
const items = [
{ id: 1, sub_items: [ { id: 1 }, { id: 2 }, { id: 3 }, ] },
{ id: 2, sub_items: [ { id: 4 }, { id: 5 }, { id: 6 }, ] },
];
const subItemIds = items.map( (item) =>
item.sub_items.map( (subItem) => subItem.id )
).flat()
console.log(subItemIds);
Array.reduce
Another method is to use reduce to iterate over the object and build an accumulation array using Array.reduce. In the example below, when pushing onto the array, the spread operator (...) is used to break the array into elements.
const items = [
{ id: 1, sub_items: [ { id: 1 }, { id: 2 }, { id: 3 }, ] },
{ id: 2, sub_items: [ { id: 4 }, { id: 5 }, { id: 6 }, ] },
];
const subItemIds = items.reduce((arr,item) => (
arr.push(...item.sub_items.map((subItem) => subItem.id)), arr
),[])
console.log(subItemIds);
Other
Other answers here make use of custom functions or Array.flatMap, which should be explored as they could lead to more readable and efficient code, depending on the program's needs.
I have two JSON arrays, would like to know the key which don't match. I don't need the value.
Example:
livetable: [
{ id: 1, name: "Sandra" },
{ id: 2, name: "John" },
],
backupTable: [
{ id: 1, name: "Sandra" },
{ id: 2, name: "Peter" },
],
I can get the key/value pair which is diffrent with this Lodash script:
difference = _.differenceWith(livetable,backupTable,_.isEqual)
But I would just need the key, in this example "name" for "id: 2" is not matching, so I would need to get the "name" key to new array/variable.
(Using VUE CLI)
EDIT: Added example of current code output.
var livetable = [{"id": 1, "name": "Sandra", "id": 2, "name": "John"}]
var backupTable = [{"id": 1, "name": "Sandra", "id": 2, "name": "Peter"}]
console.log(_.differenceWith(backupTable,livetable,_.isEqual))
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>
This will output the key:value pair, but I would just need the key which is diffrent.
I think I understand what you're trying to do. There are some unknowns though, like what should happen if there is a missing record in the second data set?
This solution assumes each table of data has the same amount of records and the records have the same IDs.
// define data
const livetable = [
{ id: 1, name: "Sandra" },
{ id: 2, name: "John" }
]
const backupTable = [
{ id: 1, name: "Sandra" },
{ id: 2, name: "Peter" }
]
const getDifferentRecordsByID = (sourceRecords, compareRecords) => {
// simple utility function to return a record object matching by ID
const findComparisionRecord = id => compareRecords.find(compareRecord => compareRecord.id === id)
// using the utility function, we can filter out any mismatching records by comparing name
return sourceRecords
.filter(sourceRecord => sourceRecord.name !== findComparisionRecord(sourceRecord.id).name)
// then map over all the records and just pull out the ID
.map(record => record.id)
}
console.log(getDifferentRecordsByID(livetable, backupTable)) // [2]
Here is working VUE code for my problem.
Function returns [ "name" ], which is exactly what I need.
data() {
return {
livetable: [{ id: 1, name: "Sandra" },{ id: 2, name: "John" }],
backupTable: [{ id: 1, name: "Sandra" },{ id: 2, name: "Peter" }],
difColumns: null,
};
},
methods: {
test3() {
let resultArray = []
this.livetable.forEach((array1, index) => {
const array2 = this.backupTable[index];
resultArray.push(this._.reduce(array1, (result, value, key) => this._.isEqual(value, array2[key]) ? result : result.concat(key), []))
});
this.difColumns = resultArray[0]
}
},
I can't figure it out how to transform and combine 2 arrays of object.
I have this 2 arrays of objects:
const selectedCourse = [
{
"courseType": [5],
"id": 26,
"title": "Apple Tart with Apricot Glaze",
},
{
"courseType": [3],
"id": 16,
"title": "Classic Caesar Salad",
},
{
"courseType": [1,2],
"id": 10,
"title": "Lobster Bisque",
},
{
"courseType": [3],
"id": 16,
"title": "Classic Caesar Salad",
},
]
const courseTypes = [
{name: "Hors d'oeuvres", id: 0},
{name: "Soup", id: 1},
{name: "Fish", id: 2},
{name: "Salad", id: 3},
{name: "Main course", id: 4},
{name: "Dessert", id: 5}
]
The courseType property inside the first JSON is an array of numbers that corresponds to courseTypes index and property id in the second JSON.
The result for this case should be this:
const result = [
{
courseType: 1,
courseName: "Soup",
courses: [
{
"courseType": [1,2],
"id": 10,
"title": "Lobster Bisque",
}
]
},
{
courseType: 3,
courseName: "Salad",
courses: [
{
"courseType": [1,2],
"id": 10,
"title": "Lobster Bisque",
}
]
},
{
courseType: 3,
courseName: "Fish",
courses: [
{
"courseType": [3],
"id": 16,
"title": "Classic Caesar Salad",
},
{
"courseType": [3],
"id": 16,
},
]
},
{
courseType: 5,
courseName: "Main course",
courses: [
{
"courseType": [5],
"id": 26,
"title": "Apple Tart with Apricot Glaze",
}
]
}
]
The expected result have to combine the 2 arrays by filtering by courseType property.
Assuming, you want all items with selectedCourse, you could take a Map and collect all courses and later greate a new array out of the found values.
This solution includes Fish as well.
const
selectedCourse = [{ courseType: [5], id: 26, title: "Apple Tart with Apricot Glaze" }, { courseType: [3], id: 16, title: "Classic Caesar Salad" }, { courseType: [1, 2], id: 10, title: "Lobster Bisque" }, { courseType: [3], id: 16, title: "Classic Caesar Salad" }],
courseTypes = [{ name: "Hors d'oeuvres", id: 0 }, { name: "Soup", id: 1 }, { name: "Fish", id: 2 }, { name: "Salad", id: 3 }, { name: "Main course", id: 4 }, { name: "Dessert", id: 5 }],
map = selectedCourse.reduce((m, o) => o.courseType.reduce((n, id) => n.set(id, [...(n.get(id) || []), o]), m), new Map),
result = courseTypes.reduce(
(r, { name: courseName, id: courseType }) => (map.get(courseType) || []).reduce((s, courses) => s.concat({ courseType, courseName, courses }), r),
[]
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could use map and filter like this:
const selectedCourse = [ { "courseType": [5], "id": 26, "title": "Apple Tart with Apricot Glaze", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, { "courseType": [1,2], "id": 10, "title": "Lobster Bisque", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, ]
const courseTypes = [ {name: "Hors d'oeuvres", id: 0}, {name: "Soup", id: 1}, {name: "Fish", id: 2}, {name: "Salad", id: 3}, {name: "Main course", id: 4}, {name: "Dessert", id: 5} ];
const result = courseTypes.map(courseType => ({
courseType: courseType.id,
courseName: courseType.name,
courses: selectedCourse.filter(course => course.courseType.includes(courseType.id))
})).filter(extended => extended.courses.length);
console.log(JSON.stringify(result, null, 2));
Explanation:
courseTypes.map iterates over your second input array and for each type it finds in selectedCourse which courses match with that particular type.
It uses .filter to collect those matches. The filter callback uses includes to determine if there is a match -- it returns a boolean, exactly what the filter callback expects as return value.
This filtered array is then added to an object literal that also defines the other two properties courseType and courseName. That new object is what the course type is mapped to. courseTypes.map returns an array of those objects.
Finally that result may have entries that have an empty courses array. Those are filtered out with another call to .filter. If the length of that courses array is non zero, the object is kept, otherwise it is kicked out of the result.
For older browsers
Here is the same code made compatible with older browsers (no arrow functions, no includes, which were introduced in ES2015):
const selectedCourse = [ { "courseType": [5], "id": 26, "title": "Apple Tart with Apricot Glaze", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, { "courseType": [1,2], "id": 10, "title": "Lobster Bisque", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, ]
const courseTypes = [ {name: "Hors d'oeuvres", id: 0}, {name: "Soup", id: 1}, {name: "Fish", id: 2}, {name: "Salad", id: 3}, {name: "Main course", id: 4}, {name: "Dessert", id: 5} ];
const result = courseTypes.map(function (courseType) {
return {
courseType: courseType.id,
courseName: courseType.name,
courses: selectedCourse.filter(function (course) {
return course.courseType.indexOf(courseType.id) > -1;
})
};
}).filter(function (extended) {
return extended.courses.length;
});
console.log(JSON.stringify(result, null, 2));
while "trincot" code is work fine for chrome and Mozila but it will not work in IE edge and IE 10 and below you need to convert it in pure javascript. below is code which will work in all browser.
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function(searchElement, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If len is 0, return false.
if (len === 0) {
return false;
}
// 4. Let n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0;
// 5. If n ≥ 0, then
// a. Let k be n.
// 6. Else n < 0,
// a. Let k be len + n.
// b. If k < 0, let k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}
// 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
if (sameValueZero(o[k], searchElement)) {
return true;
}
// c. Increase k by 1.
k++;
}
// 8. Return false
return false;
}
});
}
var selectedCourse = [{ "courseType": [5], "id": 26, "title": "Apple Tart with Apricot Glaze" }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad" }, { "courseType": [1, 2], "id": 10, "title": "Lobster Bisque" }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad" }];
var courseTypes = [{ name: "Hors d'oeuvres", id: 0 }, { name: "Soup", id: 1 }, { name: "Fish", id: 2 }, { name: "Salad", id: 3 }, { name: "Main course", id: 4 }, { name: "Dessert", id: 5 }];
var result = courseTypes.map(function (courseType) {
return {
courseType: courseType.id,
courseName: courseType.name,
courses: selectedCourse.filter(function (course) {
return course.courseType.includes(courseType.id);
})
};
}).filter(function (extended) {
return extended.courses.length;
});
console.log(JSON.stringify(result, null, 2));
I have a nested array of objects like this:
var matchs = [
{
id: 10689,
sport: 'Tennis',
players: [
{
id: 22,
name:'Rafa Nadal',
country: 'Spain',
odds: [
{id: 1, bookie_1: 1.60},
{id: 2, bookie_2: 1.61},
{id: 3, bookie_3: 1.62},
]
},
{
id: 23,
name:'Roger Federer',
country: 'Spain',
odds: [
{id: 4, bookie_1: 2.60},
{id: 5, bookie_2: 2.61},
{id: 6, bookie_3: 2.62},
]
}
]
},
{
id: 12389,
sport: 'Tennis',
players: [
{
id: 45,
name:'Fernando Verdasco',
country: 'Spain',
odds: [
{id: 7, bookie_1: 2.60},
{id: 8, bookie_2: 2.61},
{id: 9, bookie_3: 2.62},
]
},
{
id: 65,
name:'Andy Murray',
country: 'Spain',
odds: [
{id: 10, bookie_1: 1.60},
{id: 11, bookie_2: 1.61},
{id: 12, bookie_3: 1.62},
]
}
]
}
];
I want to use normalizr to simplify array and use with redux. I have read the Normalizr documentation but it has few examples and I do not know what I am doing wrong.
I have tried the following code without success. The result I get is an array with undefined.
import { normalize, schema } from 'normalizr';
const match = new schema.Entity('matchs');
const player = new schema.Entity('players');
const odd = new schema.Entity('odds');
match.define({
player: [player],
odd: [odd]
});
console.log(normalize(matchs, [match]));
I need something like this:
{
result: "123",
entities: {
"matchs": {
"123": {
id: "123",
players: [ "1","2" ],
odds: [ "1", "2" ]
}
},
"players": {
"1": { "id": "1", "name": "Rafa Nadal" },
"2": { "id": "2", "name": "Andy Murray" }
},
"odds": {
"1": { id: "1", "bookie_1": "1.20" }
"2": { id: "2", "bookie_2": "1.21" }
"3": { id: "3", "bookie_3": "1.22" }
}
}
}
I cannot find a straight solution using only normalizr, so my only choice is to pre-format the data before passing to the normalizer.
const preformattedData = data.map(sport => {
const oddArrays = sport.players.map(player => player.odds || []);
return {
...sport,
odds: [].concat.apply([], oddArrays)
}
})
const odd = new schema.Entity('odds')
const player = new schema.Entity('players',
{
odds: [ odd ]
}
)
const sport = new schema.Entity('sports',
{
players: [ player ],
odds: [odd]
}
)
const normalizedData = normalize(preformattedData, [ sport ]);
Demo: https://codesandbox.io/s/20onxowzwn
I think this is what you need
const odd = new schema.Entity('odds');
const player = new schema.Entity('players' , { odds: [ odd]});
const match = new schema.Entity('matchs', {players: [player]});
but the result will be different because your json it is structured like this, I mean, the odds key is child of players, not of matches, therefore the result will be this way.
Just take a look at the console
Here is a solution with latest version of normalizr
const odds = new schema.Entity("odds");
const players = new schema.Entity("players", {
odds: [odds]
});
const matches = new schema.Entity("matches", { players: [players] });
const normalizedData = normalize(data, [matches]);
It would group data in your question as
{
"entities": {
"odds": {
"1": {
"id": 1,
"bookie_1": 1.6
}
},
"players": {
"22": {
"id": 22,
"name": "Rafa Nadal",
"country": "Spain",
"odds": [
1,
2,
3
]
}
},
"matches": {
"10689": {
"id": 10689,
"sport": "Tennis",
"players": [
22,
23
]
}
}
},
"result": [
10689
]
}
You can achieve your desired result by tweaking the process and merge strategies. I don't have time to do the leg work for you, but I explain the approach in detail here:
https://medium.com/#JustinTRoss/normalizing-data-into-relational-redux-state-with-normalizr-47e7020dd3c1
i have two arrays ( busns and pc ) i want to check pc array -> pcid is match with busns array -> pcid after match i want to return pcname. final output is comming but i want to avoid duplicate. thanks in advance
please check my attempt in jsfiddle
const busns = [
{
id:1,
shopname:'New trend',
pcid:1
},
{
id:2,
shopname:'Latest Beauty',
pcid:2
},
{
id:3,
shopname:'Mens Style',
pcid:1
},
{
id:4,
name:'Fabulook',
pcid: 1
},
{
id:4,
name:'New cut',
pcid: 2
}
]
const pc = [
{
pcid:1,
pcname: 'collection1'
},
{
pcid:2,
pcname: 'collection2'
},
{
pcid:3,
pcname: 'collection3'
},
{
pcid:4,
pcname: 'collection4'
}
]
My code :
busns.map(busns => {
return pc.filter( p => {
return busns.pcid == p.pcid
}).map(data => {
console.log(data.pcname)
})
})
expected output while using console :
collection1
collection2
As commented, you could use this:
var ids = busns.map(x=>x.pcid); pc.filter(x=> ids.includes(x.pcid))
Your code:
What you are doing is,
Looping on business array to get current PC id.
Then you use this ID to filter out from PC's list and then use map to get name.
Now the issue with your code is, since you are looping on busns array, you are essentially printing the name of PC for every id.
const busns = [{ id: 1, shopname: 'New trend', pcid: 1 }, { id: 2, shopname: 'Latest Beauty', pcid: 2 }, { id: 3, shopname: 'Mens Style', pcid: 1 }, { id: 4, name: 'Fabulook', pcid: 1 }, { id: 4, name: 'New cut', pcid: 2 } ]
const pc = [{ pcid: 1, pcname: 'collection1' }, { pcid: 2, pcname: 'collection2' }, { pcid: 3, pcname: 'collection3' }, { pcid: 4, pcname: 'collection4' } ]
busns.map(busns => {
return pc.filter(p => {
return busns.pcid == p.pcid
}).map(data => {
console.log(data.pcname)
})
})
Solution from comment:
Instead of nested looping structure, what you can do is,
Create a list of pcids. This will help you know if pc is traded.
Loop over pc array. Trades can be many but product will be finite and less in number. Use this to get a filtered list of products that are in busns.
Now loop over this filtered array and retrieve names. This part was not covered in comment.
const busns = [{ id: 1, shopname: 'New trend', pcid: 1 }, { id: 2, shopname: 'Latest Beauty', pcid: 2 }, { id: 3, shopname: 'Mens Style', pcid: 1 }, { id: 4, name: 'Fabulook', pcid: 1 }, { id: 4, name: 'New cut', pcid: 2 } ]
const pc = [{ pcid: 1, pcname: 'collection1' }, { pcid: 2, pcname: 'collection2' }, { pcid: 3, pcname: 'collection3' }, { pcid: 4, pcname: 'collection4' } ]
var ids = busns.map(x=>x.pcid);
var pcNames = pc
.filter(x=> ids.includes(x.pcid))
.map(x=> x.pcname);
console.log(pcNames)
Preferred solution:
One issue with above approaches is extra iterations and duplicate pcid in list. So instead of using functions like .map + .filter, we can use .reduce and create unique list. This will keep iterations minimum.
Create a hashMap with keys as pcid and value as true. This will create a unique id map.
Now loop over pc array and check if current id is present in this object ot not. If present, push name. If not, continue.
I would suggest you to use this approach as this should be more performant. Using .map + .filter + .indexOf can be expensive for huge arrays.
const busns = [{ id: 1, shopname: 'New trend', pcid: 1 }, { id: 2, shopname: 'Latest Beauty', pcid: 2 }, { id: 3, shopname: 'Mens Style', pcid: 1 }, { id: 4, name: 'Fabulook', pcid: 1 }, { id: 4, name: 'New cut', pcid: 2 } ]
const pc = [{ pcid: 1, pcname: 'collection1' }, { pcid: 2, pcname: 'collection2' }, { pcid: 3, pcname: 'collection3' }, { pcid: 4, pcname: 'collection4' } ]
var ids = busns.reduce((acc, cur) => acc[cur.pcid] = true && acc, {});
var pcNames = pc.reduce((acc, cur) => {
if(ids[cur.pcid]) {
acc.push(cur.pcname);
}
return acc;
}, [])
console.log(pcNames)
Something like this.
pc.filter(p => busns.map(busns => busns.pcid).includes(p.pcid)).forEach(data => console.log(data.pcname));