I get hooked with this!

Write a function that replaces the words in raw with the words in code_words such that the first occurrence of
each word in raw is assigned the first unassigned word in code_words.
Assume that the total number of unique elements in raw string is greater than the total number of unique elements in code_words

encoder([“a”], [“1”, “2”, “3”, “4”]) → [“1”]
encoder([“a”, “b”], [“1”, “2”, “3”, “4”]) → [“1”, “2”]
encoder([“a”, “b”, “a”], [“1”, “2”, “3”, “4”]) → [“1”, “2”, “1”]
encoder([“a”, “b”, “a”, “c”], [“1”, “2”, “3”, “4”]) → [“1”, “2”, “1”, “3”]

my algorithm is:

  1. create a function that takes two arrays as an argument
  2. create newArray to hold the return
  3. convert the array to two dimensional array;
  4. loop through it and map each element with the other
  5. push the mapped element into newArray created in step 2
  6. return the newArray

but it is not working as it intends to do and am a newbies, can somebody help me out?
this my code, somebody should sincerely help me out

const list1 = ["a", "b", "a", "c"];
const list2 =  ["1", "2", "3", "4"];

 function encode(str1, str2){
     let arr2 = [];
     arr2.push(str1, str2);
    let newArr = [];
    for (var i = 0; i < arr2[0].length; i++){
        for(let j = 0; j <= i; j++){
            if(filt.includes(arr2[0][i]) ){
           // if(str[0][i] === str[1][j]){
               newArr.push(list2.charAt(j) )
    return newArr
   console.log(encode(list1, list2));

you have if(filt.includes( but filt isn’t defined right?

1 Like

I think the two dimensional array might be unnecessarily complicated. Also, I THINK you don’t need a nested for loop. You could get rid of the inner for loop. You’re always comparing the same index of both arrays right? For example, you want to add the third item in str2 to newArr if the third item in str2 isn’t present in newArr already AND str1 has a third item.

your process makes sense and you accomplished step 1, 2, 3, and 6 correctly.

first a couple semantic issues. your params are named str1 and str2 when that’s misleading. They’re arrays of strings so maybe strArr1 and 2 would be more appropriate (or something like that). Later in your for loops you reference list2 when really you should reference the encode argument that corresponds to list2.

I think if your if check was !newArr[i].includes(str2[i]) you’d be golden.

thank you so much am grateful, I am grateful