Search code examples
javascriptarraysecmascript-6ecmascript-2016

Get matching items by comparing two arrays


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;
}


Solution

  • 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 chosen attr for those objects.

    The second option folds the filter attribute key and value into an object such as {"id": ids}.

    const input = [ {id : "1" , text: "ABC", value: "abc" }, {id : "2" , text: "DEF", value: "def" },  {id : "3" , text: "LMN", value: "lmn" } ]
    
    const ids = ["1", "3"];
    const values = ["def", "lmn"];
    const texts = ["DEF", "LMN"];
    
    function getValuesOld(objects, key, keyvalues, attr) {
      return objects.filter(x => keyvalues.includes(x[key])).map(x => x[attr]);
    }
    
    console.log(getValuesOld(input, "id", ids, "text"));
    console.log(getValuesOld(input, "value", values, "id"));
    console.log(getValuesOld(input, "text", texts, "value"));
    
    function getValues(objects, key, attr) {
      const [keyname, keyvalues] = Object.entries(key)[0];
      return objects.filter(x => keyvalues.includes(x[keyname])).map(x => x[attr]);
    }
    
    console.log(getValues(input, { "id": ids }, "text"));
    console.log(getValues(input, { "value": values }, "id"));
    console.log(getValues(input, { "text": texts }, "value"));