skip to Main Content

I have two arrays:

list_a = [20, 20, 20, 21, 21, 22, 20,21, 23, 20, 23, 24]
list_b = [120, 121, 122, 123, 124]

and I want to create the next array from those two arrays like so:

newList = [120, 120, 120, 121, 121, 122, 120, 121, 123, 120, 123, 124]

so the first number from the first array will replaced by value with 120, but not in the length of the 20, and so on, and afterwards when 20 is also located, it will replace it with the first number also

I tried a lot of stuff, nothing worked…

4

Answers


  1. The specs were not clear

    Try this, we create a unique list of list_a and use the placement of each to index into list_b

    const list_a = [20, 20, 20, 21, 21, 22, 20, 21, 23, 20, 23, 24]
    const list_b = [120, 121, 122, 123, 124]
    const idxList = [...new Set(list_a)]; // unique and placements
    const newList = list_a.map(num => {
      const idx = idxList.indexOf(num)
      return list_b[idx]
    });
    
    console.log(newList)
    Login or Signup to reply.
  2. There’s probably a more elegant solution with Sets but the first thing that came to my mind was to make a hash map first and then map through the list_a array.

    This solution allows for any values in list_b but requires that the following condition is met:

    unique_values_list_b.length >= unique_values_list_a
    

    Hope this helps or sends you in the right direction.

    (function main () {
        const list_a = [20, 20, 20, 21, 21, 22, 20,21, 23, 20, 23, 24]
        const list_b = [120, 121, 122, 123, 124]
    
        let i = 0
        const hash = new Map([])
    
        // setting up a hash
        for(let a of list_a){
            if(hash.has(a)) continue
        
            hash.set(a, list_b[i++])        
        }
    
    
        // creating your new list
    
        const newList = list_a.map(element => hash.get(element))
        console.log(newList)
    })()
    Login or Signup to reply.
  3. You could take an object for the values and keep an index of unseen values.

    const
        list_a = [20, 20, 20, 21, 21, 22, 20, 21, 23, 20, 23, 24],
        list_b = [120, 121, 122, 123, 124],
        result = list_a.map(
            ((values, i) => v => values[v] ?? (values[v] = list_b[i++]))
            ({}, 0)
        );
        
    console.log(...result);
    console.log(...[120, 120, 120, 121, 121, 122, 120, 121, 123, 120, 123, 124]);
    Login or Signup to reply.
  4. let list_a = [20, 20, 20, 21, 21, 22, 20, 21, 23, 20, 23, 24];
    let list_b = [120, 121, 122, 123, 124];
    
    let output = list_a.map((e) => {
      return parseInt('1' + e);
    });
    
    console.log(output);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search