I have an array like this (arr), how do I want to get an array like (arr2)? Where the 'start' and 'end' elements are fixed values。
Original array:
var arr = [
{form: 'start', to: 'task-1'},
{form: 'start', to: 'task-4'},
{form: 'task-1', to: 'task-2'},
{form: 'task-2', to: 'end'},
{form: 'task-1', to: 'task-3'}
]
console.log(arr)
Expected array:
var arr2 = [
{form: 'start', to: 'task-1'},
{form: 'task-1', to: 'task-2'},
{form: 'task-2', to: 'end'},
]
console.log(arr2)
-
Basically, you have a graph here. So use one of the more common graph representations and run a (breadth|depth)-first-search on it.Sirko– Sirko2020年01月17日 05:31:49 +00:00Commented Jan 17, 2020 at 5:31
-
may be your expected array list seems like group by 'form' and first record 'to', Am i correct.?Chandrashekhar Komati– Chandrashekhar Komati2020年01月17日 05:35:37 +00:00Commented Jan 17, 2020 at 5:35
-
@chandukomati Yes, the first is form: start and the last is to: end25757750– 257577502020年01月17日 05:38:44 +00:00Commented Jan 17, 2020 at 5:38
2 Answers 2
Recursively find object and push to result array. Here is sample code.
var arr = [
{form: 'start', to: 'task-1'},
{form: 'start', to: 'task-4'},
{form: 'task-1', to: 'task-2'},
{form: 'task-2', to: 'end'},
{form: 'task-1', to: 'task-3'}
]
const getTo = search => arr.find(x => x.form === search).to;
let form = 'start';
let to = '';
const res = [];
while (to !== 'end') {
to = getTo(form);
res.push({form, to});
form = to;
}
console.log(res)
answered Jan 17, 2020 at 5:58
Siva Kondapi Venkata
11.1k2 gold badges20 silver badges32 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Sirko
This seems to assume, that there is only one element per
form entry. How does your algorithm cope with the duplicates like the two from: 'task-1' elements?Siva Kondapi Venkata
@Sirko, Yes, my assumption is that finds the first element in duplicates. Based on the output mentioned in question and summary, "recursive " approach to get the path, this will be sample solution. Agree that this will not address duplicates. There can be lot of variations to it,
getting all possible paths, or get short path (less nodes) or long path etc.Here is it.
var arr = [
{form: 'start', to: 'task-1'},
{form: 'start', to: 'task-4'},
{form: 'task-1', to: 'task-2'},
{form: 'task-2', to: 'end'},
{form: 'task-1', to: 'task-3'}
]
// console.log(arr);
const obj = arr.reduce((accum, value) => {
const formId = value.form;
const to = value.to;
if (!accum[formId]) {
accum[formId] = to;
}
return accum;
}, {});
const arr2 = Object.entries(obj).map(([key, value]) => {
return {
form: key,
to: value
}
});
console.log(arr2);
answered Jan 17, 2020 at 5:47
CHANist
1,4431 gold badge15 silver badges40 bronze badges
lang-js