skip to Main Content

I have an 2 Array

var arr1 = ['A','B','C','D']
var arr2 = ['A~XX','A~XXX','B~YY','B~YYY']

I want push arr2 elements that contains ‘A’ to op_array

var op_array = new Array();

my op_array should look like this, If ‘A’ is passed this

['A~XX','A~XXX']

If ‘B’ is passed then

['B~YY','B~YYY']

I have been trying this

op_array = arr1.filter(item => !arr2.split(/~/)[1].includes(item));

Curious to learn an efficient way.

2

Answers


  1. If you plan to do make lookup many times, say more than log(n) times, it makes sense to pre-create some sort of a set or dictionary for fast and efficient way.

    var arr1 = ['A','B','C','D']
    var arr2 = ['A~XX','A~XXX','B~YY','B~YYY']
    
    const dict = arr2.reduce(function(agg, item) {
      var pair = item.split("~")
      agg[pair[0]] = agg[pair[0]] || []
      agg[pair[0]].push(item)
      return agg
    }, {})
    
    // console.log(dict)
    
    function make_op_array(letter) {
      return dict[letter]
    }
    
    console.log(make_op_array('A'))
    Login or Signup to reply.
    1. The issue is that arr2.split(/~/) doesn’t work on the entire array. The split method works on strings, not arrays, and you need to apply it individually to each element of arr2.
    2. Also, the filter you used is trying to compare values in arr1 instead of focusing on arr2.

      Try with below code

      var arr1 = ['A', 'B', 'C', 'D'];
      var arr2 = ['A~XX', 'A~XXX', 'B~YY', 'B~YYY'];
      
      function my_function(letter) {
          var op_array = [];
          
          for (const item of arr2) {
              const [firstPart] = item.split('~');
              if (firstPart === letter) {
                  op_array.push(item); 
              }
          }
          
          return op_array;
      }
      
      console.log(my_function('A'));  // Output: ['A~XX', 'A~XXX']
      console.log(my_function('B'));  // Output: ['B~YY', 'B~YYY']
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search