I want to pick the value of the given key and I did this using a ugly code: (I used two for loops to do a simple task)
const phrases = [
{0: "i was sent", 1: "have you ever"},
{2: "look", 3: "looked", 4: "looked", 5: "at", 6: "at"},
{7: "someone", 8: "somebody", 9: "to earth", 10: "sam"},
{11: "to protect"},
{12: "us", 13: "to earth"},
{14: "us", 15: "you"}
];
const result = getSpanIDText(8); // get value of 8 im the above array
console.log(result);
function getSpanIDText(spanID) {
for (let i = 0; i < phrases.length; i++) {
const set = phrases[i]; // each object inside phrases array
for (const [key, value] of Object.entries(set)) {
if (parseInt(key) === spanID) {
return value;
}
}
}
}
I wonder if there is a more clear code not need two for loops to achive the same result?
5 Answers 5
This would eliminate the nested for loop, a little bit easier to read.
function getSpanIDText(spanID) {
for(let phrase of phrases) {
if(phrase[spanID]) {
return phrase[spanID];
}
}
}
Comments
I guess you could do something like this, provided you're sure each object will contain unique number keys.
let item = phrases.map(obj => Object.entries(obj)).flat().filter(arr => arr[0] == spanId);
return item.length ? item[0][1] : false;
Gives
getSpanIDText(8); //"somebody"
Comments
I don't know if it's really better but the following should work as well
function getSpanId(phrases, spanId) {
return new Map(phrases.map(Object.entries).flat()).get(spanId)
}
Comments
Try this.
const phrases = [
{0: "i was sent", 1: "have you ever"},
{2: "look", 3: "looked", 4: "looked", 5: "at", 6: "at"},
{7: "someone", 8: "somebody", 9: "to earth", 10: "sam"},
{11: "to protect"},
{12: "us", 13: "to earth"},
{14: "us", 15: "you"}
];
const result = getSpanIDText(8);
function getSpanIDText(id) {
let output
phrases.forEach(x => {
return Object.keys(x).forEach(y => {
if (+y === id) {
output = x[y];
}
});
});
return output;
}
console.log(result);
Comments
You could use an optimized reduce function.
When the reduce function finds a matching key, it mutates the duplicated array to break out of the reduce loop.
const phrases = [
{0: "i was sent", 1: "have you ever"},
{2: "look", 3: "looked", 4: "looked", 5: "at", 6: "at"},
{7: "someone", 8: "somebody", 9: "to earth", 10: "sam"},
{11: "to protect"},
{12: "us", 13: "to earth"},
{14: "us", 15: "you"}
];
function getSpan(phrases, key) {
return phrases.slice(0).reduce((acc, cv, i, arr) => {
if (key in cv) {
arr = [];
return cv[key];
}
return acc
}, undefined)
}
console.log(getSpan(phrases, 8)) // "somebody"
console.log(getSpan(phrases, 22)) // undefined