Filter an Array based on multiple values - arrays

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))

Related

Handling relational data in Zustand

I need some input from people more experienced with Zustand to share their way of managing relational state. Currently we have the following:
Let's assume we have the example entities Campaign, Elementss and their Settings. The REST API returning them is in the following format:
GET <API>/campaigns/1?incl=elements,elements.settings
{
"id":1,
"name":"Welcome Campaign",
"elements":[
{
"id":5,
"type":"heading",
"label":"Heading",
"content":"Welcome!",
"settings":[
{
"id":14,
"name":"backgroundColor",
"value":"#ffffff00"
},
{
"id":15,
"name":"color",
"value":"#ffffff00"
}
]
},
{
"id":6,
"type":"button",
"label":"Button",
"content":"Submit",
"settings":[
{
"id":16,
"name":"backgroundColor",
"value":"#ffffff00"
},
{
"id":17,
"name":"color",
"value":"#ffffff00"
},
{
"id":18,
"name":"borderRadius",
"value":"3px"
}
...
]
}
...
]
}
What we are currently doing in the Reactjs app is fetching this data, then transforming it to the following normalized format and set functions:
const useCurrentCampaignStore = create(
combine(
{
campaign: {
id: 1,
name: "Welcome Campaign"
},
elements: [
{
id: 5,
campaignId: 1,
type: "heading",
label: "Heading",
content: "Welcome!"
},
{
id: 6,
campaignId: 1,
type: "button",
label: "Button",
content: "Submit"
}
],
settings: [
{
id: 14,
elementId: 5,
name: "backgroundColor",
value: "#ffffff00"
},
{
id: 15,
elementId: 5,
name: "color",
value: "#ffffff00"
},
{
id: 16,
elementId: 6,
name: "backgroundColor",
value: "#ffffff00"
},
{
id: 17,
elementId: 6,
name: "disabled",
value: false
},
{
id: 18,
elementId: 6,
name: "borderRadius",
value: 3,
}
]
},
set => ({
updateSetting: (id: string | number, newValue: string | number | boolean) =>
set(state => {
const settings = [...state.settings];
return {
...state,
settings: settings.map(setting => {
if (setting.id == id) {
return { ...setting, value: newValue };
}
return setting;
})
};
}),
updateElementContent: (id: string | number, newValue: string) => {
set(state => {
const elements = [...state.elements];
return {
...state,
elements: elements.map(element => {
if (element.id == id) {
return { ...element, content: newValue };
}
return element;
})
};
});
}
})
)
);
I am, however, not sure this is the optimal solution, because It's rather tedious transforming all GET requests to a normalized format and then converting them back to nested objects when you want to construct either a POST, PUT or PATCH request.
So, to put it short, how do you guys design the state in your Zustand-based RESTful-API-backed React apps?

Update objects in an array inside map Function React or React-Hooks or React-Native

it is deleting all objects except last one from the array instead of updating a property of all objects, want to update 'ItemDeliveryStatus' of all objects inside map function
const [arrayList, setArrayList] = useState([
{ Id: 1, Name:'A', ItemDeliveryStatus:1 },
{ Id: 2, Name:'B', ItemDeliveryStatus:1 },
{ Id: 3, Name:'C', ItemDeliveryStatus:1 },
{ Id: 4, Name:'D', ItemDeliveryStatus:1 },
])
const [returnCount, setReturnCount ]=useState(0)
const updateAllObjects=()=>
{
arrayList.map(items=>
{
if(items.ItemDeliveryStatus==1)
{
setArrayList([{ ...items, ItemDeliveryStatus:4}])
}
if (items.ItemDeliveryStatus==4)
{
setReturnCount(prev=>prev+1)
}
})
}
final Result Should be like this
([
{ Id: 1, Name:'A', ItemDeliveryStatus:4 },
{ Id: 2, Name:'B', ItemDeliveryStatus:4 },
{ Id: 3, Name:'C', ItemDeliveryStatus:4 },
{ Id: 4, Name:'D', ItemDeliveryStatus:4 },
])
You can update like this for all object:
const updateAllObjects = (value) => {
setArrayList(
arrayList.map((item) => {
if (item.ItemDeliveryStatus == 1) {
return { ...item, ItemDeliveryStatus: value };
};
return item;
})
);
};

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 multiple objects from a list objects by a property array?

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)

Resources