Replacing the elements of an array with elements from another array

I have an array say var array1=[“a”, “d”, “a”, “f”]; var array2=[“1”, “2”, “3”, “4”]
I want my output to be like so: [“1”, “2”, “1”, "3]

this is what I have so far:

function encoderSolution( raw, codeWords) {
    var newArray = [], i = 0;
    if(raw.length > codeWords.length){
        raw.length = codeWords.length;
    for(i; i < raw.length; i++){
            newArray.splice(i, 1, codeWords[i]);
    return newArray;

I believe you are missing a portion of the problem description in the question. How are we supposed to figure out the output from the two inputs? I understand that you are encoding, but do you mind explaining the rules for encoding.

After this I would be happy to help you understand the problem

My takeaway here is that you’re associating each leftside element with a rightside element in a way that if a leftside element was to repeat then you’d replace it with its rightside equivalent. By doing this some rightside elements will be lost.

Is that true?

Yes @luishendrix92
I am trying to replace each element in the left array with the elements in the right array of equivalent position but in a case where I encounter duplicate value, assign the same value to both …

I would suggest looking at the findIndex function of arrays. It returns the index of the first item in the array that fits a condition. Ex

var array = ['a','b','c']

var indexOfB = array.findIndex(function(item){
  return item === 'b'

//output: 1

The nice thing about this function is that findIndex returns the first index that the function returns true for. So for example if you use in on your first array and look for a you will always get index 0

Defo you’d only need indexOf since there’s no special condition other than finding said item.


The algoritm is as follows:

Declare newArray = []

Iterate array1 with currentItem
  declare itemIndex = first index of currentItem in array1
  declare newItem = array2[itemIndex]

  add newItem to newArray if newItem exists