0

Hie All,

I have two arrays as below:

var arr1 = [ '1956888670', '2109171907', '298845084' ];
var arr2 = [ 
  { KEY: '1262875245', VALUE: 'Vijay Kumar Verma' },
  { KEY: '1956888670', VALUE: 'Sivakesava Nallam' },
  { KEY: '2109171907', VALUE: 'udm analyst' },
  { KEY: '298845084', VALUE: 'Mukesh Nagora' },
  { KEY: '2007285563', VALUE: 'Yang Liu' },
  { KEY: '1976156380', VALUE: 'Imtiaz Zafar' },
  ];

arr1 has keys and arr2 has key and value. i want to output key and value of only those keys which are present in arr1. Hence my output should be,

[{ KEY: '1956888670', VALUE: 'Sivakesava Nallam' },
  { KEY: '2109171907', VALUE: 'udm analyst' },
  { KEY: '298845084', VALUE: 'Mukesh Nagora' },]

Requesting your help to write a function to fetch required output using javascript.Thanks in advance.

3
  • 1
    eh... simple for loop? Commented Aug 31, 2016 at 14:16
  • it sounds like you want to loop through arr1 (should look at for loops and how to find the length of an array). The structure would be like for every value in arr1, (depending on arr1's value), get a value from arr2 Commented Aug 31, 2016 at 14:19
  • There are countless similar questions. In search OP should thrust. Commented Aug 31, 2016 at 14:45

3 Answers 3

1
 var arr1 = [ '1956888670', '2109171907', '298845084' ];
var arr2 = [ 
  { KEY: '1262875245', VALUE: 'Vijay Kumar Verma' },
  { KEY: '1956888670', VALUE: 'Sivakesava Nallam' },
  { KEY: '2109171907', VALUE: 'udm analyst' },
  { KEY: '298845084', VALUE: 'Mukesh Nagora' },
  { KEY: '2007285563', VALUE: 'Yang Liu' },
  { KEY: '1976156380', VALUE: 'Imtiaz Zafar' },
  ];


  result = arr2.filter( function(obj) {
    return arr1.indexOf(obj.KEY) >= 0;
  });

  console.info(result);
Sign up to request clarification or add additional context in comments.

Comments

0

You can try with filter - Array.prototype.filter():

var output = arr2.filter(function(item) {
  return arr1.indexOf(item.KEY) >= 0;
});

Comments

0

You could use Set for the filtering.

var arr1 = ['1956888670', '2109171907', '298845084'],
    arr2 = [{ KEY: '1262875245', VALUE: 'Vijay Kumar Verma' }, { KEY: '1956888670', VALUE: 'Sivakesava Nallam' }, { KEY: '2109171907', VALUE: 'udm nalyst' }, { KEY: '298845084', VALUE: 'Mukesh Nagora' }, { KEY: '2007285563', ALUE: 'Yang Liu' }, { KEY: '1976156380', VALUE: 'Imtiaz Zafar' }],
    mySet = new Set,
    result;

arr1.forEach(function (a) {
    mySet.add(a);
});

result = arr2.filter(function (a) {
    return mySet.has(a.KEY);
});

console.log(result);

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.