I have two dynamic array. One is Array of objects and another one is array of some string.
First Array is :
const initialColumns = [
{content: "Registered Name", id: "name"},
{ content: "Application No", id: "application" },
{ content: "Form Name", id: "form" },
{ content: "Registered Email", id: "email" },
{ content: "Registered Mobile", id: "mobile" },
{ content: "Payment Status", id: "payment" },
{ content: "State", id: "State"},
{ content: "City", id: "City" },
{ content: "Village", id: "Village" },
{ content: "Skype", id: "Skype" },
{ content: "Lead Stage", id: "Lead Stage" },
{ content: "Lead Type", id: "Lead Type" }];
Second Array is :
const columns = ["State", "City", "Village"]
Now I would like to remove some object from the first array. That object should be removed which id doesn't exist in the second array. But the objects with id email, name, application, form, mobile, payment should not be removed.
Basically I would like to remove all item which id dosen't exist in the second array. But the objects with id email, name, application, form, mobile, payment should not be removed.
Final array should be like this :
const initialColumns = [
{content: "Registered Name", id: "name"},
{ content: "Application No", id: "application" },
{ content: "Form Name", id: "form" },
{ content: "Registered Email", id: "email" },
{ content: "Registered Mobile", id: "mobile" },
{ content: "Payment Status", id: "payment" },
{ content: "State", id: "State"},
{ content: "City", id: "City" },
{ content: "Village", id: "Village" },
CodePudding user response:
Try this
initialColumns.filter((column, idx) => idx < 6 || columns.includes(column.id))
CodePudding user response:
slice()
to take part of the array and not to modify the existing
filter()
for filtering out values
includes()
to check if array contains specific element
const filtered = initialColumns.slice(6).filter(c=>columns.includes(c.id))
now when you have filtered values you can combine with first 6 values
const finalResult = initialColumns.slice(0,6).concat(filtered);
Docs: slice, fiter, includes, concat
CodePudding user response:
const initialColumns = [
{content: "Registered Name", id: "name"},
{ content: "Application No", id: "application" },
{ content: "Form Name", id: "form" },
{ content: "Registered Email", id: "email" },
{ content: "Registered Mobile", id: "mobile" },
{ content: "Payment Status", id: "payment" },
{ content: "State", id: "State"},
{ content: "City", id: "City" },
{ content: "Village", id: "Village" },
{ content: "Skype", id: "Skype" },
{ content: "Lead Stage", id: "Lead Stage" },
{ content: "Lead Type", id: "Lead Type" }];
const columns = ["State", "City", "Village"]
const final=[]
for(let i of initialColumns){
if(columns.includes(i.content) || columns.includes(i.id)){
if(i.content==i.id){
final.push(i)
}
else{
pass
}
}
else if(i.content!=i.id){
final.push(i)
}
else{
{}
}
}
console.log(final)