2

I have two arrays in javascript(Jquery 3.2). One array (source) has key-value pairs and other(target) has values only. I want to return those key-values from source which has matching values in other(target) array. Here are the arrays.

var source = [{ "a": 3 }, { "b": 2 }, { "c": 1 },{"k":12}];
var target = ["a", "b", "c","d"];
2
  • So what is your expected output? [{ "a": 3 }, { "b": 2 }, { "c": 1 }] perhaps? Also, what have you tried so far? Commented Jul 27, 2018 at 15:40
  • @JosephMarikle [{ "a": 3 }, { "b": 2 }, { "c": 1 }] is the expected output and I was trying it with forEach loop for both arrays which i knew was wrong, thats why asked here. Commented Jul 27, 2018 at 20:53

4 Answers 4

3

You can filter the source base on the target by checking the first key in each source item. But this assumes the source items will only have one key. This will fail if there are items like {a: 3, d:4}.

var source = [{ "a": 3 }, { "b": 2 }, { "c": 1 }, {"k":12}];
var target = ["a", "b", "c","d"];

let filtered = source.filter(item => target.includes(Object.keys(item)[0]))
console.log(filtered)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you and everyone. I was trying it with forEach(), this works perfect and limitations duly noted.
1

var source = [{ "a": 3 }, { "b": 2 }, { "c": 1 },{"k":12}];
var target = ["a", "b", "c","d"];

console.log(
  //filter the sources on the target values
  source.filter(function(element){
    //should show the element, if the key is in the target list
    return target.indexOf(Object.keys(element)[0]) > -1;
  })
);

Comments

1

One option is to use set on target, this will make it easier to check if the set has a certain element. Use filter to filter the source array.

var source = [{ "a": 3 }, { "b": 2 }, { "c": 1 },{"k":12}];
var target = ["a", "b", "c", "d"];

var tempSet = new Set(target);
var result = source.filter(o => tempSet.has(Object.keys(o)[0]));

console.log(result);

Comments

1

There are different was to do this.One of them using filter is as below:

var source = [{ "a": 3 }, { "b": 2 }, { "c": 1 },{"k":12}];
var target = ["a", "b", "c","d"];
var filteredArray  = source.filter(function(array_el){
   return target.filter(function(target_el){
      return target_el == Object.keys(array_el);
   }).length > 0
});
console.log(filteredArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.