How to filter multiple objects from a list objects by a property array? - arrays

I have a object array in which each object contain an id and a name and a separate array contains a set of ids. I want to filter first array based on the second array.
const data= [
{
id: 1,
name: 'name1'
},
{
id: 2,
name: 'name2'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];
const array = [1,3,4];
const expectedResult= [
{
id: 1,
name: 'name1'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];

Use .filter and .includes
const data= [
{
id: 1,
name: 'name1'
},
{
id: 2,
name: 'name2'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];
const array = [1, 3, 4]
const result = data.filter((item) => {
//gives us items that passes a condition
return array.includes(item.id)
})
console.log(result)

Related

How do i map through array to get array of object?

I have an array called data. How do i extract sub_data? Just need the sub_data part for each object.
const data = [
{
id: 1,
title: 'Logo'
sub_data: [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
},
{
id: 2,
title: 'Brands'
sub_data: [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
}
]
Example output will get two outputs because there is 2 objects:
const subData = [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
const subData = [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
Not very sure how to use the map function just to get sub_data in the correct structure
You can use flatMap to get sub_data in one array
const data = [
{
id: 1,
title: 'Logo',
sub_data: [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
},
{
id: 2,
title: 'Brands',
sub_data: [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
}
]
const result = data.flatMap(item => item.sub_data)
console.log(result)
If you want an array with the sub_data objects you can just map the original array:
const data = [
{
id: 1,
title: 'Logo',
'sub_data'
: [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
},
{
id: 2,
title: 'Brands',
sub_data: [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
}
]
const mappedData = data.flatMap(obj => obj.sub_data)
console.log(mappedData)
Another solution would be to use the .forEach function of javascript.
const subData = [];
data.forEach(item => subData.push(...item.sub_data))

How to manipulate the object inside the array using javascript?

var arr = [
{ id: 1, name: 'Ahmed Malick', school: 'TEWGS' },
{ id: 2, name: 'Tehmeed Anwar', school: 'DGS' },
{ id: 3, name: 'Azhar Yameen', school: 'DGS' }
]
I want this output:
The student name is his id is and he studies in
Can you please show me what kind of output you expect. Then i will try to solve it.
I'm not sure if this is what you want
var arr = [
{ id: 1, name: "Ahmed Malick", school: "TEWGS" },
{ id: 2, name: "Tehmeed Anwar", school: "DGS" },
{ id: 3, name: "Azhar Yameen", school: "DGS" },
];
arr.map((student) => {
return `Name: ${student.name}, id: ${student.id}, he studies in: ${student.school}`;
}).forEach((output) => {
console.log(output);
});
If you want it in the DOM do this
let html = arr.map((student) => {
return `<p><strong>Name</strong>: ${student.name}, <strong>id</strong>: ${student.id},<strong> he studies in</strong> ${student.school}</p>`;
}).join("")
document.createElement("div").innerHTML = html
Try thatGood luck

Create new array using 2 arrays with Map function in Angular

Is there an efficient way of creating a new array from 2 arrays?
var employees1 = [
{ id: 11, name: 'joe' },
{ id: 12, name: 'mike' },
{ id: 13, name: 'mary' },
{ id: 14, name: 'anne' }
];
var employees2 = [
{ id: 11, message: 'test1' },
{ id: 12, message: 'test2' },
{ id: 13, message: 'test3' },
{ id: 14, message: 'test4' }
];
Iterate employees1 array and get 'message' for matching id from employees2. Resulting in new array:
var employees3 = [
{ id: 11, name: 'joe', message: 'test1' },
{ id: 12, name: 'mike', message: 'test2' },
{ id: 13, name: 'mary', message: 'test3' },
{ id: 14, name: 'anne', message: 'test4' }
];
Is this possible using Map function? Or using a standard foreach suggested?
Iterate over the first array, search for the element in the second array and finally push them to the new array as illustrated below:
var employees3 = [];
employees1.forEach(emp1 => {
const findEmp = employees2.find(emp2 => emp2.id === emp1.id);
if (findEmp) {
employees3.push({
...emp1,
...findEmp
});
}
});
console.log(employees3);
You can use Array#map and Array#find to get the desired output. I am attaching a sample code:
var employees3 = employees1.map(emp => ({
...emp,
...(employees2.find(item => item.id === emp.id) ?? {})
}))

How to filter array based on id in angularJS

i have multiple data for one id , i want filter my data like this
$scope.mpArray =[
{ Id: 1, Name: Madhu, Address: Upal },
{ Id: 1, Name: Chandu, Address: Upal },
{ Id: 2, Name: Srinu, Address: Kphb },
{ Id: 2, Name: Vijay, Address: kphb },
{ Id: 3, Name: Ajay, Address: Banglore },
{ Id: 3, Name: Narsi, Address: Banglore },
{ Id: 3, Name: Peter, Address: Banglore },
];
i want to filter my array like this
var FilterArray = [
{ Id: 1,Madhu, Chandu},
{ Id: 2, Srinu, Vijay},
{ Id: 3, Ajay, Narsi, Peter},
];
At first you need to change your FilterArray to
[
{
"Id": 1,
"Name": [
"Madhu",
"Chandu"
]
},
{
"Id": 2,
"Name": [
"Srinu",
"Vijay"
]
},
{
"Id": 3,
"Name": [
"Ajay",
"Narsi",
"Peter"
]
}
]
Notice that name is an array. The FilterArray of your question
var FilterArray = [
{ Id: 1,Madhu, Chandu},
{ Id: 2, Srinu, Vijay},
{ Id: 3, Ajay, Narsi, Peter},
];
Do not contain a valid JSON object inside the array so you need to change the structure to the one where add a new key Name in the JSON object of FilterArray as like the first structure above. Then the below code works great.
$(document).ready(function(){
var myArray =[
{ Id: 1, Name: "Madhu", Address: "Upal" },
{ Id: 1, Name: "Chandu", Address: "Upal" },
{ Id: 2, Name: "Srinu", Address: "Kphb" },
{ Id: 2, Name: "Vijay", Address: "kphb" },
{ Id: 3, Name: "Ajay", Address: "Banglore" },
{ Id: 3, Name: "Narsi", Address: "Banglore" },
{ Id: 3, Name: "Peter", Address: "Banglore" },
];
var FilterArray = [];
var matched;
for(var i=0;i<myArray.length; i++){
matched = false;
var myArrayId = myArray[i].Id;
for(var j=0; j<FilterArray.length; j++){
var FilterArrayId = FilterArray[j].Id;
if(myArrayId === FilterArrayId){
matched = true;
FilterArray[j].Name.push(myArray[i].Name);
// no need to loop further
break;
}
}
if(!matched){
var obj = {
'Id' : myArrayId,
'Name' : [myArray[i].Name],
}
FilterArray.push(obj);
}
}
console.log(FilterArray);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
try this
var mpArray =[
{ Id: 1, Name: 'Madhu', Address: 'Upal' },
{ Id: 1, Name: 'Chandu', Address: 'Upal' },
{ Id: 2, Name: 'Srinu', Address: 'Kphb' },
{ Id: 2, Name: 'Vijay', Address: 'kphb' },
{ Id: 3, Name: 'Ajay', Address: 'Banglore' },
{ Id: 3, Name: 'Narsi', Address: 'Banglore' },
{ Id: 3, Name: 'Peter', Address: 'Banglore' },
];
var filterObject = {};
mpArray.forEach(function (item) {
if (!filterObject[item.Id]) {
filterObject[item.Id] = [];
}
filterObject[item.Id].push(item.Name);
});
console.log(filterObject);
$scope.mpArray =[
{ Id: 1, Name: 'Madhu', Address: 'Upal' },
{ Id: 1, Name: 'Chandu', Address: 'Upal' },
{ Id: 2, Name: 'Srinu', Address: 'Kphb' },
{ Id: 2, Name: 'Vijay', Address: 'kphb' },
{ Id: 3, Name: 'Ajay', Address: 'Banglore' },
{ Id: 3, Name: 'Narsi', Address: 'Banglore' },
{ Id: 3, Name: 'Peter', Address: 'Banglore' },
];
var FilterArray = [];
var FilteredArrayIds=[];
$scope.mpArray.forEach(
function(detailObj) {
if(FilteredArrayIds.indexOf(detailObj.Id)==-1)
return FilteredArrayIds.push(detailObj.Id);
});
for(var i=0; i<FilteredArrayIds.length;i++)
{
var result = $scope.mpArray.filter(function( obj ) {
return obj.Id == FilteredArrayIds[i];
});
var rsltNames = result.map(function(obj){
return obj.Name;
})
var filteredObj ={
id:FilteredArrayIds[i]+',' +rsltNames.join()
}
FilterArray.push(filteredObj);
}
console.log(filteredObj)

Filter an Array based on multiple values

I have the following simple JSON array:
const personList = [
{
id: 1,
name: "Phil"
},
{
id: 2,
name: "Bren"
},
{
id: 3,
name: "Francis Underwood"
},
{
id: 4,
name: "Claire Underwood"
},
{
id: 5,
name: "Ricky Underwood"
},
{
id: 6,
name: "Leo Boykewich"
}
];
And I would like to filter this by passing an array of ids so something like [1,4] would be passed in and it would only return "Phill" and "Claire Underwood"
This is what the function looks like but I know it's wrong attendeeIds is an array that's passed in [1, 4]:
getAttendeesForEvent: (attendeeIds) => {
if (attendeeIds === undefined) return Promise.reject("No attendee id provided");
return Promise.resolve(personList.filter(x => x.id == [attendeeIds]).shift());
}
I haven't used JS in years. I've looked for examples but they all seem too complex for what I'm trying to achieve. So how can I filter this based on an array of id's passed in?
return Promise.resolve(personList.filter(x => attendeeIds.indexOf(x.id) !== -1));
You want to check if the id of each item your looping over exists inside of attendeeIds. Use Array.indexOf inside of the filter to do that.
This will return an array of { id: #, name: String } objects.
If you want to return just the names of those objects, you can do a map afterwards which will transform an array into another array using the function that you provide.
const filteredNames = personList
.filter(x => attendeeIds.indexOf(x.id) !== -1)
.map(x => x.name);
// ['Phil', 'Claire Underwood']
You could do something in these lines. Hope this helps.
const personList = [{
id: 1,
name: "Phil"
}, {
id: 2,
name: "Bren"
}, {
id: 3,
name: "Francis Underwood"
}, {
id: 4,
name: "Claire Underwood"
}, {
id: 5,
name: "Ricky Underwood"
}, {
id: 6,
name: "Leo Boykewich"
}];
let attendeeIds = [1, 5];
let getAttendeesForEvent = () => {
return new Promise(function(resolve, reject) {
if (attendeeIds === undefined) {
reject("No attendee id provided");
} else {
resolve(personList.filter((x) => attendeeIds.includes(x.id)).map((obj) => obj.name));
}
});
}
getAttendeesForEvent().then((data) => console.log(data))

Resources