I have to arrays:
var shortcuts = [
{"name":"Pan", "alias":["Pan","Pan_he"]},
{"name":"Print Map","alias":["PrintMap"]}
];
var toolbarDef =[
{"name":"Pan_he","alias":["Select","Select_he"]},
{"name":"Draw","alias":["Point","SetDot"]},
{"name":"Find","alias":["OnMap","FromArea"]},
{"name":"PrintMap","alias":["Pentagon"]},
{"name":"Buffer","alias":["Layer","ShowData"]}
]
I need to remove from toolbarDef array all objects where the property of the name equals for one of the items of alias array in shortcuts array of objects.
Here the array that I expect to get based on shortcuts and toolbarDef objects array:
var result =[
{"name":"Draw","alias":["Point","SetDot"]},
{"name":"Find","alias":["OnMap","FromArea"]},
{"name":"Buffer","alias":["Layer","ShowData"]}
]
Here how I try to achive this result:
var result = toolbarDef.filter( function( item ) {
return !shortcuts.find(function(shortcut) {
return shortcut.alias.forEach(function(a){
return a === item.name
})
})
});
but result has the same rows as toolbarDef array.
My question is how can I achieve the desire result and why code above dosen't do the job?
-
2forEach doesn't return anything.Harsha Venkataramu– Harsha Venkataramu2020年10月06日 19:42:04 +00:00Commented Oct 6, 2020 at 19:42
2 Answers 2
Build an array of elements to remove, and then filter out the ones you don't want:
var shortcuts = [
{"name":"Pan", "alias":["Pan","Pan_he"]},
{"name":"Print Map","alias":["PrintMap"]}
];
var toolbarDef =[
{"name":"Pan_he","alias":["Select","Select_he"]},
{"name":"Draw","alias":["Point","SetDot"]},
{"name":"Find","alias":["OnMap","FromArea"]},
{"name":"PrintMap","alias":["Pentagon"]},
{"name":"Buffer","alias":["Layer","ShowData"]}
]
let toRemove = shortcuts.flatMap(({alias}) => alias)
console.log(toolbarDef.filter(({name}) => !toRemove.includes(name)));
btw return shortcut.alias.forEach wont works since forEach does not return anything
Comments
On your code, instead of using Array.forEach, you should use Array.some.
Array.forEach returns nothing.
var result = toolbarDef.filter(function(item) {
return !shortcuts.find(function(shortcut) {
return shortcut.alias.some(function (a) {
return a === item.name;
});
});
});
Here's the working example.
const shortcuts = [
{"name":"Pan", "alias":["Pan","Pan_he"]},
{"name":"Print Map","alias":["PrintMap"]}
];
const toolbarDef = [
{"name":"Pan_he","alias":["Select","Select_he"]},
{"name":"Draw","alias":["Point","SetDot"]},
{"name":"Find","alias":["OnMap","FromArea"]},
{"name":"PrintMap","alias":["Pentagon"]},
{"name":"Buffer","alias":["Layer","ShowData"]}
];
// Your Code Fix
var result = toolbarDef.filter(function(item) {
return !shortcuts.find(function(shortcut) {
return shortcut.alias.some(function (a) {
return a === item.name;
});
});
});
console.log(result);
// Simple Case
const result1 = toolbarDef.filter(({ name }) => !shortcuts.some(({ alias }) => alias.includes(name)));
console.log(result1);