DEV Community

loading...

Algorithms and Scripting: Problems and Notes Part 3

Randy Rivera
Once I truly put my mind on something, I won't ever stop.
Updated on ・2 min read

Today is a Wednesday, I will continue to try and post every week, including the weekends. (most likely Sunday Mornings) Sometimes life catches up to you and they're things going on but I and you should make time for the things we want to achieve.

  • Anyways Let's continue. This particular problem will want us to write a function that takes two or more arrays and returns a new array of unique values. Basically all values that are there from all arrays should be inluded but no duplicates in the final array.
  • An example of this would be if an array includes [1, 2, 3], [5, 2, 1] then we should should return [1, 2, 3, 5] Here 1 is a duplicate.
  • Code:
function unique(arr) {
  return arr;
}

unique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function unique(arr) {
  let numbers = [...arguments]
  let results = []
  for (let i = 0; i < numbers.length; i++) {
    for (let j = 0; j < numbers[i].length; j++) {
      if (results.indexOf(numbers[i][j]) === -1) {
        results.push(numbers[i][j])
      }
     }
    }
 return results;
}
console.log(unique([1, 3, 2], [5, 2, 1, 4], [2, 1])); will display [1, 3, 2, 5, 4]
Enter fullscreen mode Exit fullscreen mode

Convert HTML entities

  • Here they want us to create a program that will convert HTML entities from string to their corresponding HTML entities such as &, <, >, " (double quote), and "'" (apostrophe).
  • Code
function convert(str) {
  return str;
}

convertHTML("Pasta < Tacos < Pizza");
Enter fullscreen mode Exit fullscreen mode
  • Answer:
 function change(character) {
    if (character === "&") {
      return "&amp;";
    } else if (character === "<") {
      return "&lt;";
    } else if (character === ">") {
      return "&gt;";
    } else if (character === '"') {
      return "&quot;";
    } else if (character === "'") {
      return "&apos;";
    }
   }

    function convert(str) {
      let focused = ["&", "<", ">", "'", '"'];
      for (let i = 0; i < str.length; i++) {
       if (focused.indexOf(str[i]) != -1) {
         str = str.slice(0, i) + change(str[i]) + str.slice(i + 1)
      }
     }
  return str;
}

console.log(convert("Pasta < Tacos < Pizza")); 
 // will display Pasta &lt; Tacos &lt; Pizza
Enter fullscreen mode Exit fullscreen mode

Discussion (0)