Untitled
user_9196400
plain_text
2 years ago
1.4 kB
11
Indexable
// description: key is a have dictionary is b
// b can also key of other dictonary
//INPUT
const arr =[{ A: 'B'},{B:'C'},{C:'D'},{D:'E'},{E:'F'}, {F:'A'}, {H:'K'}, {K:'H'}]
/*expect:
A -F
B-F
C-F
D-F
E-F
*/
//SOLUTION
const keyValue = arr.reduce(function(result, item) {
var key = Object.keys(item)[0];
result[key] = item[key];
return result;
}, {});
//array key to loop
const mainKey = arr.flatMap(Object.keys)
const result ={}
let count =0;
for (let i=0; i< mainKey.length;i++) {
count +=1
let middleDictionary =[]
let key = mainKey[i]
let dictionary = keyValue[key]
if(result[dictionary]) {result[key] = result[dictionary];continue;}
if (!result[key]) result[key] =dictionary;
while(keyValue[dictionary])
{
dictionary = keyValue[dictionary]
if (dictionary == key)
break;
count+=1
middleDictionary.push(dictionary)
}
if(middleDictionary.length)
{
for(let j=0; j< middleDictionary.length; j++) {
//for case final dictionary - final dictionary
result[middleDictionary[j]] = dictionary
}
}
result[key] =dictionary
}
const arrRes = Object.keys(result).map(i=> ({key :i, dictionary : result[i]}))
console.log('input key-dictionary is ', arr)
console.log('array key is',mainKey)
console.log('object have only key-value is', keyValue)
console.log('result is',result)
console.log('count is ', count)
console.log('final arr result', arrRes)Editor is loading...