I'm still learning basics of map(), filter(), forEach(), and includes() and can't seem to figure out the best way or anyway of attempting this...
Let's say I've got an arr and an obj and I need to return the object values if object key is in the array
const array = [1, 2, 3];
const object = { 1: "blue", 2: "red", 3: "green", 4: "orange", 5: "purple" };
I believe because I'm going for a new array, I need to use map()
You can use Object.entries(object) to get an array of key value pairs of the object, then filter according to the array elements, finally map and return only the values:
const array = [1, 2, 3];
const object = { 1: "blue", 2: "red", 3: "green", 4: "orange", 5: "purple" };
const result = Object.entries(object).filter(el=>array.includes(parseInt(el[0]))).map(el=>el[1])
console.log(result)
Or if you want to keep the order order of the elements (thanks to ASDFGerte), just map over the array and return the value of the element.
const array = [3,2,1];
const object = { 1: "blue", 2: "red", 3: "green", 4: "orange", 5: "purple" };
const result = array.map(el => object[el]);
console.log(result)
We will only be returning values with keys that are present in the array. So you can simply iterate through the array values, and check if there is a value in the object with the array value as the key. Since you want it to return the values from the call itself maybe we can use reduce:
let values = array.reduce((found, item) => {
return (item in object) ? found.push(object[item]) && found : found
}, [])
console.log(values)