I have an array of objects that look like this
const input = [ {id : "1" , text: "ABC", value: "abc" }, {id : "2" , text: "DEF", value: "def" }, {id : "3" , text: "LMN", value: "lmn" } ]
The above wrapper function when passed respective inputs, should return the following
const ids = ["1", "3"]
const values = ["def", "lmn"]
const texts = ["DEF", "LMN"]
getValues(input, ids, "text") // ["ABC", "LMN"]
getValues(input, values, "id") // ["2", "3"]
getValues(input, texts, "value") // ["def", "lmn"]
When group of ids
are passed and when required field is text
it should return the matching text
values from the input array. Same goes when values
and id
is passed as required fields, it should return all matching ids
from input
Code I tried
function getValues(input1, input2, field){
const result = input1.map(({id, text, value}) => {
if(text === input2){
return input1[field];
}
});
return result;
}
2
Answers
const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
const matchingItems = array1.filter(item => array2.includes(item));
console.log(matchingItems); // Output: [3, 4, 5]
Here are two general purpose functions that filter a list of objects for a given key attribute whose value is in a provided list of
keyvalues
, and then returns the chosenattr
for those objects.The second option folds the filter attribute key and value into an object such as
{"id": ids}
.