The code works with a simple foreach function, but not with a find method.
Here is the forEach code:
getItemById: function (id) {
let found = null;
data.items.forEach(item => {
if (item.id === id) {
found = item;
}
});
return found;
}
Here is the code with a find mehtod:
getItemById: function (id) {
let item = data.items.find(item => {
item.id === id;
});
return item;
}
Why doesn't work the code with the find method?
also here is the array of the objects:
const data = {
items: [
{ id: 0, name: 'Steak Dinner', calories: 1200 },
{ id: 1, name: 'Sausage', calories: 1100 },
{ id: 2, name: 'Eggs', calories: 200 },
],
currentItem: null,
totalCalories: 0,
}
The find expects a predicate function as a callback and return the value that satisfy the condition. If you won't return then undefined will return by default and undefined is considered as a falsy value.
You are not returning anything from the find function. find will not consider a match if predicate function won't return true. There is not a single match that returns true in any case because all values returned by find is undefined
return item.id === id.
const data = {
items: [
{ id: 0, name: "Steak Dinner", calories: 1200 },
{ id: 1, name: "Sausage", calories: 1100 },
{ id: 2, name: "Eggs", calories: 200 },
],
currentItem: null,
totalCalories: 0,
};
const obj = {
getItemById: function (id) {
let item = data.items.find((item) => {
return item.id === id;
});
return item;
},
};
console.log(obj.getItemById(0));
You're not returning the boolean inside find's callback
let item = data.items.find(item => {
return item.id === id;
});
You just forgot the return statement in your find function. So it will run through all items and result nothing currently.
So just return the result of item.id === id and you're fine.
let item = data.items.find(item => {
return item.id === id;
});
getItemById: function (id) {
return data.items.find(item => item.id === id);
}
You don't have to use "{" and ";" in data.items.find() method. Because,the find is a predicate function
If a lambda function contains a single expression, it is returned automatically. (; and {} are not part of an expression )
Otherwise the return statement is a must, to return a value.
find accepts a predicate & such it must return a boolean.
Either do,
let item = data.items.find(item => item.id === id);
Or,
let item = data.items.find(item => {
return item.id === id;
});
Related
I have a custom object that is defined as following (names and properties have been simplified to avoid confidential information leakage):
type T = {
id: number;
title: string;
};
This type is used to create a list of Ts like so:
const IT: StringMap<T> = {
a: {
id: 0,
title: 'foo',
},
b: {
id: 1,
title: 'bar',
},
c: {
id: 2,
title: 'foobar',
},
}
I need a way to be able to retrieve one of these T type objects based on their id. So I created the following function:
const getTUsingId = (ts: StringMap<T>, id: number): T => {
Object.values(ts).forEach((t: T) => {
if (t.id === id) {
return t
}
});
// This is as a safeguard to return a default value in case an invalid id is passed
return ts['a']
}
For whatever reason, this function will always return ts['a'] regardless of what id I pass to it. Console logging t.id === id even returns true but it still carries on until the end of the ts map!
Any help is highly appreciated!
return won't break out of your loop. You need to use a plain for loop:
const getTUsingId = (ts: StringMap<T>, id: number): T => {
for (const t of Object.values(ts)) {
if (t.id === id) {
return t
}
}
return ts['a']
}
the forEach callback is for performing an action on every element in the array, it's return isn't used for termination, what you want is filter, find or a regular for loop
Object.values(ts).filter((t: T) => {
return t.id === id;
});
return all values where the id matches as a fresh array, you would use this if there was a possibility of multiple match, you would then need to parse the returned array to decide which match was correct
Object.values(ts).find((t: T) => {
return t.id === id;
});
return only the first matching value
for(const t of Object.values(ts))
if (t.id === id) {
return t
}
});
my preference would be find
const getTUsingId = (ts: StringMap<T>, id: number): T => {
return Object.values(ts).find((t: T) => t.id === id) ?? ts['a']
}
I'm trying to get a tree segment based on an id. The id may be at the root, or anywhere in the children. My goal is to get that entire family tree line, and not other non-related data.
I have the entire data tree, and an id.
The idea is to do this recursively, since the number of children is unknown.
import "./styles.css";
export default function App() {
const folderTree = [
{
id: "1-1",
children: [
{
id: "1-2",
parentId: "1-1",
children: []
}
]
},
{
id: "2-1",
children: [
{
id: "2-2",
parentId: "2-1",
children: [
{
id: "2-4",
parentId: "2-2",
children: []
}
]
},
{
id: "2-3",
parentId: "2-1",
children: []
}
]
}
];
const getRelatedTreeFolders = (folders, selectedFolderId) => {
//** goes top to bottom
const recursiveChildCheck = (folder, id) => {
// THIS trial failed
// let foundNested = false;
// if (folder.id === id) {
// return true;
// }
// function recurse(folder) {
// if (!folder.hasOwnProperty("children") || folder.children.length === 0)
// return;
// for (var i = 0; i < folder.children.length; i++) {
// if (folder.children[i].id === id) {
// foundNested = true;
// break;
// } else {
// if (folder.children[i].children.length > 0) {
// recurse(folder.children[i].children);
// if (foundNested) {
// break;
// }
// }
// }
// }
// }
// recurse(folder);
// return foundNested;
const aChildHasIt =
folder.children.length > 0 && folder.children.some((f) => f.id === id);
if (aChildHasIt) return true;
let nestedChildHasIt = false;
/** The problem seems to be here */
folder.children.forEach((childFolder) => {
// Is using a forEach loop the correct way?
// ideally it seems there is a simple way to do a recursive .some on the dhildren...
childFolder.children.length>0 && recursiveChildCheck(childFolder, id)
});
if (nestedChildHasIt) return true;
folder.children && folder.children.forEach(recursiveChildCheck);
};
const treeSegment = folders.reduce((result = [], folder) => {
if (
folder.id === selectedFolderId ||
recursiveChildCheck(folder, selectedFolderId)
) {
result.push(folder);
}
return result;
}, []);
return treeSegment;
};
const selectedFolderId = "2-1";
const selectedFolderId1 = "2-2";
const selectedFolderId2 = "2-4";
const selectedFolderId3 = "2-3";
const selectedFolderId4 = "3-1";
const selectedFolderId5 = "1-1";
const selectedFolderId6 = "1-2";
console.log("parent");
console.log(getRelatedTreeFolders(folderTree, selectedFolderId));
console.log("child");
console.log(getRelatedTreeFolders(folderTree, selectedFolderId1));
console.log("grandchild"); // this fails
console.log(getRelatedTreeFolders(folderTree, selectedFolderId2));
console.log("sibling");
console.log(getRelatedTreeFolders(folderTree, selectedFolderId3));
console.log("not found");
console.log(getRelatedTreeFolders(folderTree, selectedFolderId4));
console.log("other parent");
console.log(getRelatedTreeFolders(folderTree, selectedFolderId5));
console.log("other child");
console.log(getRelatedTreeFolders(folderTree, selectedFolderId6));
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
{/* <h2>{JSON.stringify(result)}</h2> */}
</div>
);
}
Some issues:
recursiveChildCheck is supposed to return a boolean, but in some cases nothing (undefined) is returned, because a return statement is missing in the following expression:
folder.children && folder.children.forEach(recursiveChildCheck);
Moreover, in the expression above, the second operand of the && operator will never be evaluated, because folder.children is an array, and arrays are always truthy, even empty arrays. To give the second operand a chance, the first operand should be folder.children.length > 0
But even with that correction, the second operand will always evaluate to undefined, as that is what .forEach returns by design. You should have a method call there that returns a boolean, like some.
nestedChildHasIt never gets any other value after its initialisation, and so the following return true will never happen:
if (nestedChildHasIt) return true;
You may have intended to set nestedChildHasIt to true in the preceding forEach loop, but it seems like you have an alternative way here to do the same as the other forEach loop you had at the end.
I think the issue you have been struggling with is that you need to both check a boolean condition (does the subtree have the id?) and you need to filter the children to the child for which this is true, creating a new node which has this unique child.
Corrected code:
function getForestSegment(nodes, id) {
function recur(nodes) {
for (const node of nodes) {
if (node.id === id) return [node];
const children = recur(node.children);
if (children.length) return [{ ...node, children}];
}
return [];
}
return recur(nodes);
}
// Example from question:
const forest = [{id: "1-1",children: [{id: "1-2",parentId: "1-1",children: []}]},{id: "2-1",children: [{id: "2-2",parentId: "2-1",children: [{id: "2-4",parentId: "2-2",children: []}]},{id: "2-3",parentId: "2-1",children: []}]}];
for (const id of ["2-1", "2-2", "2-4", "2-3", "3-1", "1-1", "1-2"]) {
console.log(id);
console.log(getForestSegment(forest, id));
}
I have a list of object
let table = [{id:4,val:"21321"},{id:5,val:"435345"},{id:6,val:"345345"}]
I want to rename the id value after removing an object from the list which has a specific id value(for example id:5)
I am using array filter method
table.filter((element,index)=>{
if(element.id!==5){
element.id=index
return element
}else{
index+1
}
return null
})
I am expecting a return value
[{id: 0,val: "21321"},{id: 1,val: "345345"}]
but i am getting this
[{id: 0, val: "21321"},{id: 2, val: "345345"}]
Note: I know i can use filter method to remove the specific object and than use map method to rename the id value but i want a solution where i have to use only one arrow function
You can use array#reduce to update the indexes and remove elements with given id. For the matched id element, simply return the accumulator and for other, add new object with val and updated id.
const data = [{ id: 4, val: "21321" }, { id: 5, val: "435345" }, { id: 6, val: "345345" }],
result = data.reduce((res, {id, val}) => {
if(id === 5) {
return res;
}
res.push({id: res.length + 1, val});
return res;
}, []);
console.log(result)
This would do it:
let table = [[{id:4,val:"21321"},{id:5,val:"435345"},{id:6,val:"345345"}]];
let res=table[0].reduce((a,c)=>{if(c.id!=5){
c.id=a.length;
a.push(c)
}
return a}, []);
console.log([res])
The only way to do it with "a single arrow function" is using .reduce().
Here is an extremely shortened (one-liner) version of the same:
let res=table[0].reduce((a,c)=>(c.id!=5 && a.push(c.id=a.length,c),a),[]);
Actually, I was a bit premature with my remark about the "only possible solution". Here is a modified version of your approach using .filter() in combination with an IIFE ("immediately invoked functional expression"):
table = [[{id:4,val:"21321"},{id:5,val:"435345"},{id:6,val:"345345"}]];
res= [ (i=>table[0].filter((element,index)=>{
if(element.id!==5){
element.id=i++
return element
} }))(0) ];
console.log(res)
This IIFE is a simple way of introducing a persistent local variable i without polluting the global name space. But, stricly speaking, by doing that I have introduced a second "arrow function" ...
It probably is not the best practice to use filter and also alter the objects at the same time. But you would need to keep track of the count as you filter.
let table = [[{id:4,val:"21321"},{id:5,val:"435345"},{id:6,val:"345345"}]]
const removeReorder = (data, id) => {
var count = 0;
return data.filter(obj => {
if (obj.id !== id) {
obj.id = count++;
return true;
}
return false;
});
}
console.log(removeReorder(table[0], 5));
It is possible to achieve desired result by using reduce method:
const result = table.reduce((a, c) => {
let nestedArray = [];
c.forEach(el => {
if (el.id != id)
nestedArray.push({ id: nestedArray.length, val: el.val });
});
a.push(nestedArray);
return a;
}, [])
An example:
let table = [[{ id: 4, val: "21321" }, { id: 5, val: "435345" }, { id: 6, val: "345345" }]]
let id = 5;
const result = table.reduce((a, c) => {
let nestedArray = [];
c.forEach(el => {
if (el.id != id)
nestedArray.push({ id: nestedArray.length, val: el.val });
});
a.push(nestedArray);
return a;
}, [])
console.log(result);
The main issue in your code is filter method is not returning boolean value. Use the filter method to filter items and then use map to alter object.
let table = [
[
{ id: 4, val: "21321" },
{ id: 5, val: "435345" },
{ id: 6, val: "345345" },
],
];
const res = table[0]
.filter(({ id }) => id !== 5)
.map(({ val }, i) => ({ id: i, val }));
console.log(res)
Alternatively, using forEach with one iteration
let table = [[{id:4,val:"21321"},{id:5,val:"435345"},{id:6,val:"345345"}]]
const res = [];
let i = 0;
table[0].forEach(({id, val}) => id !== 5 && res.push({id: i++, val}));
console.log(res)
I am doing this:
case LOAD_PAGES:
return {
...state,
pages: [...state.pages, action.pages],
};
And I have a component that every time I enter to it, it send the same data to the store so I am getting lots of duplicate data.
The pages array looks like this:
pages: [
{
key: 0,
menuName: 'Home',
pageType: 'HomePage',
dataIndex: 'HomePage0'
},
{
key: 1,
menuName: 'Employer Chat',
pageType: 'EmployerChat',
dataIndex: 'EmployerChat1'
},
]
This is the React component:
const handlePageLoad = () => {
if (siteById.data) {
siteById.data.pages.map((p, index) => {
return loadPagesAction({
key: index,
menuName: p.menuName,
pageType: p.pageType,
dataIndex: p.pageType + index,
});
});
}
};
useEffect(() => {
if (siteById.data.pages.length) {
handlePageLoad();
}
}, []);
Any ideas?
Here's "smart" way to filter duplicates.
function filterDuplicates(array, areEqual) {
return array.filter((item, pos) => {
return array.findIndex((other) => areEqual(item, other)) == pos;
});
}
console.log(
filterDuplicates([
{ key: 1, name: 'test' },
{ key: 2, name: 'apple' },
{ key: 1, name: 'test' },
], (a, b) => a.key == b.key)
);
Pass array to first argument and equality comparer to second argument of filterDuplicates. I got this idea from that answer.
TypeScript
function filterDuplicates<T>(array: T[], areEqual: ((a: T, b: T) => boolean)): T[] {
return array.filter((item: T, pos: number) => {
return array.findIndex((other: T) => areEqual(item, other)) == pos;
});
}
You can do something like this :
Check if there is an existing page in your state or not, if return same or else push
case LOAD_PAGES:
return {
...state,
pages: state.pages.findIndex(page => page.key === action.pages.key) >= 0 ?
state.pages :
[...state.pages, action.pages]
};
There are many ways to solve your problem and here is how I would approach it:
Instead of using an array, store your pages in an object and use the already defined keys as keys for the object. You can use Object.values(store.pages) or Object.entries(store.pages) to get an array of the pages the way you did before.
Simply using set, the duplicated element can be omitted.
return { ...state, arr: Array.from(new Set([...state.arr, ...newArr]))};
I am trying to return a specific node in a JSON object structure which looks like this
{
"id":"0",
"children":[
{
"id":"1",
"children":[...]
},
{
"id":"2",
"children":[...]
}
]
}
So it's a tree-like child-parent relation. Every node has a unique ID.
I'm trying to find a specific node like this
function findNode(id, currentNode) {
if (id == currentNode.id) {
return currentNode;
} else {
currentNode.children.forEach(function (currentChild) {
findNode(id, currentChild);
});
}
}
I execute the search for example by findNode("10", rootNode). But even though the search finds a match the function always returns undefined. I have a bad feeling that the recursive function doesn't stop after finding the match and continues running an finally returns undefined because in the latter recursive executions it doesn't reach a return point, but I'm not sure how to fix this.
Please help!
When searching recursively, you have to pass the result back by returning it. You're not returning the result of findNode(id, currentChild), though.
function findNode(id, currentNode) {
var i,
currentChild,
result;
if (id == currentNode.id) {
return currentNode;
} else {
// Use a for loop instead of forEach to avoid nested functions
// Otherwise "return" will not work properly
for (i = 0; i < currentNode.children.length; i += 1) {
currentChild = currentNode.children[i];
// Search in the current child
result = findNode(id, currentChild);
// Return the result if the node has been found
if (result !== false) {
return result;
}
}
// The node has not been found and we have no more options
return false;
}
}
function findNode(id, currentNode) {
if (id == currentNode.id) {
return currentNode;
} else {
var result;
currentNode.children.forEach(function(node){
if(node.id == id){
result = node;
return;
}
});
return (result ? result : "No Node Found");
}
}
console.log(findNode("10", node));
This method will return the node if it present in the node list. But this will loop through all the child of a node since we can't successfully break the forEach flow. A better implementation would look like below.
function findNode(id, currentNode) {
if (id == currentNode.id) {
return currentNode;
} else {
for(var index in currentNode.children){
var node = currentNode.children[index];
if(node.id == id)
return node;
findNode(id, node);
}
return "No Node Present";
}
}
console.log(findNode("1", node));
I use the following
var searchObject = function (object, matchCallback, currentPath, result, searched) {
currentPath = currentPath || '';
result = result || [];
searched = searched || [];
if (searched.indexOf(object) !== -1 && object === Object(object)) {
return;
}
searched.push(object);
if (matchCallback(object)) {
result.push({path: currentPath, value: object});
}
try {
if (object === Object(object)) {
for (var property in object) {
if (property.indexOf("$") !== 0) {
//if (Object.prototype.hasOwnProperty.call(object, property)) {
searchObject(object[property], matchCallback, currentPath + "." + property, result, searched);
//}
}
}
}
}
catch (e) {
console.log(object);
throw e;
}
return result;
}
Then you can write
searchObject(rootNode, function (value) { return value != null && value != undefined && value.id == '10'; });
Now this works on circular references and you can match on any field or combination of fields you like by changing the matchCallback function.
Since this old question has been brought back up, here's a different approach. We can write a fairly generic searchTree function which we then use in a findId function. searchTree does the work of traversing the object; it accepts a callback as well as the tree; the callback determines if a node matches. As well as the node, the callback is supplied two functions, next and found, which we call with no parameters to signal, respectively, that we should proceed or that we've found our match. If no match is found, we return null.
It looks like this:
const searchTree = (fn) => (obj) =>
Array.isArray(obj)
? obj.length == 0
? null
: searchTree (fn) (obj [0]) || searchTree (fn) (obj .slice (1))
: fn (
obj,
() => searchTree (fn) (obj .children || []),
() => obj
)
const findId = (target, obj) => searchTree (
(node, next, found) => node.id == target ? found () : next(),
) (tree)
const tree = {id: 1, name: 'foo', children: [
{id: 2, name: 'bar', children: []},
{id: 3, name: 'baz', children: [
{id: 17, name: 'qux', children: []},
{id: 42, name: 'corge', children: []},
{id: 99, name: 'grault', children: []}
]}
]}
console .log (findId (42, tree))
console .log (findId (57, tree))
This code is specific to the structure where subnodes are found in an array under the property children. While we can make this more generic as necessary, I find this a common structure to support.
There is a good argument that this would be better written with mutual recursion. If we wanted, we could get the same API with this version:
const searchArray = (fn) => ([x, ...xs]) =>
x === undefined
? null
: searchTree (fn) (x) || searchArray (fn) (xs)
const searchTree = (fn) => (obj) =>
fn (
obj,
() => searchArray (fn) (obj .children || []),
(x) => x
)
This works the same way. But I find the code cleaner. Either should do the job, though.
We use object-scan for our data processing needs. It's conceptually very simple, but allows for a lot of cool stuff. Here is how you could solve your question
// const objectScan = require('object-scan');
const findNode = (id, input) => objectScan(['**'], {
abort: true,
rtn: 'value',
filterFn: ({ value }) => value.id === id
})(input);
const data = { id: '0', children: [{ id: '1', children: [ { id: '3', children: [] }, { id: '4', children: [] } ] }, { id: '2', children: [ { id: '5', children: [] }, { id: '6', children: [] } ] }] };
console.log(findNode('6', data));
// => { id: '6', children: [] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
Similar questions were answered several times, but I just want to add a universal method that includes nested arrays
const cars = [{
id: 1,
name: 'toyota',
subs: [{
id: 43,
name: 'supra'
}, {
id: 44,
name: 'prius'
}]
}, {
id: 2,
name: 'Jeep',
subs: [{
id: 30,
name: 'wranger'
}, {
id: 31,
name: 'sahara'
}]
}]
function searchObjectArray(arr, key, value) {
let result = [];
arr.forEach((obj) => {
if (obj[key] === value) {
result.push(obj);
} else if (obj.subs) {
result = result.concat(searchObjectArray(obj.subs, key, value));
}
});
console.log(result)
return result;
}
searchObjectArray(cars, 'id', '31')
searchObjectArray(cars, 'name', 'Jeep')
I hope this helps someone
I really liked a tree search! A tree is an extremely common data structure for most of today's complex structured tasks. So I just had similar task for lunch too. I even did some deep research, but havent actually found anything new! So what I've got for you today, is "How I implemented that in modern JS syntax":
// helper
find_subid = (id, childArray) => {
for( child of childArray ) {
foundChild = find_id( i, child ); // not sub_id, but do a check (root/full search)!
if( foundChild ) // 200
return foundChild;
}
return null; // 404
}
// actual search method
find_id = (id, parent) => (id == parent.id) : parent : find_subid(id, parent.childArray);
Recursive structure search, modification, keys/values adjustments/replacement.
Usage Example:
const results = []; // to store the search results
mapNodesRecursively(obj, ({ v, key, obj, isCircular }) => {
// do something cool with "v" (or key, or obj)
// return nothing (undefined) to keep the original value
// if we search:
if (key === 'name' && v === 'Roman'){
results.push(obj);
}
// more example flow:
if (isCircular) {
delete obj[key]; // optionally - we decide to remove circular links
} else if (v === 'Russia') {
return 'RU';
} else if (key.toLocaleLowerCase() === 'foo') {
return 'BAR';
} else if (key === 'bad_key') {
delete obj[key];
obj['good_key'] = v;
} else {
return v; // or undefined, same effect
}
});
Tips and hints:
You can use it as a search callback, just return nothing (won't affect anything) and pick values you need to your Array/Set/Map.
Notice that callback is being run on every leaf/value/key (not just objects).
Or you can use the callback to adjust particular values and even change keys. Also it automatically detects circular loops and provides a flag for you to decide how to handle them.
The code
(uses ES6)
Function itself + some example demo data
function mapNodesRecursively(obj, mapCallback, { wereSet } = {}) {
if (!wereSet) {
wereSet = new Set();
}
if (obj && (obj === Object(obj) || Array.isArray(obj))) {
wereSet.add(obj);
for (let key in obj) {
if (!obj.hasOwnProperty(key)){
continue;
}
let v = obj[key];
const isCircular = wereSet.has(v);
const mapped = mapCallback({ v, key, obj, isCircular });
if (typeof (mapped) !== 'undefined') {
obj[key] = mapped;
v = mapped;
}
if (!isCircular) {
mapNodesRecursively(v, mapCallback, { wereSet });
}
}
}
return obj;
}
let obj = {
team: [
{
name: 'Roman',
country: 'Russia',
bad_key: 123,
},
{
name: 'Igor',
country: 'Ukraine',
FOO: 'what?',
},
{
someBool: true,
country: 'Russia',
},
123,
[
1,
{
country: 'Russia',
just: 'a nested thing',
a: [{
bad_key: [{
country: 'Russia',
foo: false,
}],
}],
},
],
],
};
// output the initial data
document.getElementById('jsInput').innerHTML = JSON.stringify(obj, null, 2);
// adding some circular link (to fix with our callback)
obj.team[1].loop = obj;
mapNodesRecursively(obj, ({ v, key, obj, isCircular }) => {
if (isCircular) {
delete obj[key]; // optionally - we decide to remove circular links
} else if (v === 'Russia') {
return 'RU';
} else if (key.toLocaleLowerCase() === 'foo') {
return 'BAR';
} else if (key === 'bad_key') {
delete obj[key];
obj['good_key'] = v;
} else {
return v;
}
});
// output the result - processed object
document.getElementById('jsOutput').innerHTML = JSON.stringify(obj, null, 2);
.col {
display: inline-block;
width: 40%;
}
<div>
<h3>Recursive structure modification, keys/values adjustments/replacement</h3>
<ol>
<li>
Replacing "Russia" values with "RU"
</li>
<li>
Setting the value "BAR" for keys "FOO"
</li>
<li>
Changing the key "bad_key" to "good_key"
</li>
</ol>
<div class="col">
<h4>BEFORE</h4>
<pre id="jsInput"></pre>
</div>
<div class="col">
<h4>AFTER</h4>
<pre id="jsOutput"></pre>
</div>
</div>