const objects = [...];
const ids = [1,2,3,8,9];
const missed = objects.filter(obj => !ids.includes(obj.id));
// проиндексируем по ключам
const [rootIndex, idIndex] = array.reduce(([roots, ids], obj) => {
(roots[obj.root_id] ??= []).push(obj);
ids[obj.id] = obj;
return [roots, ids];
}, [{}, {}]);
// и найдем по нему нужные объекты:
const objectsWithoutExistingParent = Object.keys(rootIndex).filter(key => !idIndex.hasOwnProperty(key)).flatMap(key => rootIndex[key]);
console.log(objectsWithoutExistingParent);
const roots = [];
COLLECT_ROOTS:
for (const n of arr) {
for (const m of arr) {
if (m.id === n.root_id) {
continue COLLECT_ROOTS;
}
}
roots.push(n);
}
// или
const roots = arr.filter(function(n) {
return !this.has(n.root_id);
}, new Set(arr.map(n => n.id)));
// или
const roots = (function get(i, n = arr[i]) {
return n
? [].concat(arr.every(m => m.id !== n.root_id) ? n : [], get(-~i))
: []
})(0);
function createTree({
data,
key = 'id',
parentKey = 'parentId',
childrenKey = 'children',
}) {
const tree = Object.fromEntries(data.map(n => [
n[key],
{ ...n, [childrenKey]: [] },
]));
return Object.values(tree).filter(n => (
!tree[n[parentKey]]?.[childrenKey].push(n)
));
}
const tree = createTree({
data: arr,
parentKey: 'root_id',
});
const mapIds = {}
const filtered = array.filter(elem => {
const existingElement = mapIds[elem.id]
if (!existingElement)
mapIds[elem.id] = elem
else
existingElement.array1.push(...elem.array1)
return !existingElement
})
const mapIds = {}
const filtered = array.filter(elem =>
(!mapIds[elem.id] && (mapIds[elem.id] = elem)) || !mapIds[elem.id].array1.push(...elem.array1)
)
const key = 'workplace';
const values = [ 'office', 'hotel' ];
const result = arr.filter(function(n) {
return this.has(n[key]);
}, new Set(values));
// или
const result = values.flatMap(((grouped, n) => grouped[n] ?? []).bind(
null,
arr.reduce((acc, n) => ((acc[n[key]] = acc[n[key]] ?? []).push(n), acc), {})
));
// или
const result = [];
for (const n of arr) {
for (const m of values) {
if (m === n[key]) {
result.push(n);
break;
}
}
}
// или
const result = [];
for (let i = 0; i < arr.length; i++) {
if (~values.indexOf(arr[i][key])) {
result[result.length] = arr[i];
}
}
// или
const result = (function get(i, n = arr[i]) {
return n
? [].concat(values.includes(n[key]) ? n : [], get(-~i))
: [];
})(0);
var arr = [{ "Name": "Alex", "sex":"man","age":50,"workplace":"office"},
{"Name": "Katya", "sex":"woman","age":33,"workplace":"office"},
{"Name": "Igor", "sex":"man","age":22,"workplace":"park"},
{"Name": "Olga", "sex":"woman","age":19,"workplace":"park"},
{"Name": "Maks", "sex":"man","age":40,"workplace":"hotel"}
var arr2 = [];
for(var prop in arr){
if(arr[prop].workplace == "office" || arr[prop].workplace == "hotel"){
arr2.push(arr[prop]);
}
}