Freecodecamp JavaScript elementary algorithm question-2

Posted by syed on Tue, 01 Feb 2022 17:21:37 +0100

Then continue to write the last article.
5. Find the largest number in multiple arrays
Input: largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])
Output: [27, 5, 39, 1001]
Solution:

function largestOfFour(arr) {
  let temp = [];
  for(let i =0;i<arr.length;i++) {
    temp.push(Math.max(...arr[i]));
  }
  return temp;
}

Idea:
The title gives the array in the array. It is required to calculate the maximum value in each internal array and then form an array to return.
First, define a new array to store the maximum value, and then traverse the small array in the large array arr, using math Max method finds the maximum value and then push es it into the new array.

6. Confirm end
Check whether the string (first parameter str) ends with the given target string (second parameter target).
Input: confirmending ("consolidation", "on")
Output: true
Solution 1:

function confirmEnding(str, target) {
  let len = target.length;
  if(str.substring(str.length-len)=== target){
    return true;
  }else{
    return false;
  }
}

Idea:
To judge whether a string ends with a string, first think of the substring method in js, and then substring will think of the end of the string, which is the reciprocal substring. Therefore, first calculate the size of the target substring, and then use the substring method to confirm whether the reciprocal substring is the same as the target string. If it is the same, it will return true, and vice versa.
Knowledge point: substring method of string. substring(str.length-x) represents the character from the penultimate index to the end.

Solution 2:

function confirmEnding(str, target) {
  if(str.endsWith(target)) {
    return true;
  }else{
    return false;
  }
}

Idea: solution 2 is relatively simple. You can directly use the js built-in endsWith method to judge whether a string is the last character of a string, but do not use it if the problem requires endsWith method, so the first substring is good.

7. Duplicate output string
Repeat a given string str (the first parameter) to output num (the second parameter) times. If num is not a positive number, an empty string is returned. In this challenge, please do not use JavaScript built - in repeat() method.
Solution 1:

function repeatStringNumTimes(str, num) {
  let temp = str;
  if(num <=0) {
    str = "";
  }
  for(let i = 0;i<num-1;i++)  {
    str +=temp;
  }
  return str;
}

Idea:
The stupidest idea is to repeatedly accumulate the number of iterations if the output is repeated. First assign the string to a temporary variable, and then accumulate the number of iterations and copies according to num-1 to str.
Solution 2:

function repeatStringNumTimes(str, num) {
  if(num <=0) {
    str = "";
  }else{
    str = str.repeat(num);
  }
  return str;
  
}

Idea:
Solution 2 uses the method repeat that the topic does not allow to be used, which can be filled in the number of times to be copied.
Knowledge points: repeat method

8. Truncate string
If the length of the incoming string (the first parameter) is greater than the incoming value (the second parameter), please truncate it at this position and add, Then return the result.
Input: truncatestring ("a-task a green and yellow basket", 8)
Output: A-tisket

Solution:

function truncateString(str, num) {
  if(str.length >num ){
    str = str.slice(0,num)+'...';
  }
  return str;
}

Idea:
First compare the length of the string and the size of num, and then use slice to intercept the string "..."

9. Filter arrays by parameters
Input: findelement ([1, 3, 5, 8, 9, 10], function (Num) {return num% 2 = = = 0;})
Output: 8
Input: findelement ([1, 3, 5, 9], function (Num) {return num% 2 = = = 0;})
Output: undefined
Solution:

function findElement(arr, func) {
  for(let i = 0;i<arr.length;i++) {
    if(func(arr[i])){
      return arr[i];
    }
    if(i==arr.length-1 && func(arr[i]) === false ){
      return undefined;
    }
  }
}

Idea:
Traverse the filter, the most stupid method, and then update it with good ideas.
10. Checking Boolean values of basic types
Check whether a value is a boolean type and return true or false
Solution:

function booWho(bool) {
  if(typeof bool === "boolean"){
    return true;
  }else{
    return false;
  }
}

11. Capitalize words in sentences
Please capitalize the first letter of each word in the incoming string and return it. Note that all characters except the initial letter should be lowercase.
Enter: titleCase("I'm a little tea pot")
Output: I'm A Little Tea Pot

Solution:

function titleCase(str) {
            var lowerStr = str.toLowerCase();  //Convert all to lowercase first
            var splitArr = lowerStr.split(' ');      //Split into arrays
            for(var i=0;i<splitArr.length;i++){
                splitArr[i] = splitArr[i][0].toUpperCase()+splitArr[i].substring(1,splitArr[i].length); //Loop and assign a value to each item
            }
            str = splitArr.join(' ');     //Splice into string
            return str;
        }

12. Slice and Splice
The input parameters of this challenge are two arrays and an index value.
Copy all the elements in the first array to the second array in turn.
Please note that you need to insert from where the index value of the second array is n.
Finally, return the array after inserting the element. The two arrays as input parameters should remain unchanged before and after the function is executed.
Input: frankenSplice([1, 2, 3], [4, 5], 1)
Output: [4, 1, 2, 3, 5]
Input: frankenSplice([1, 2, 3, 4], [], 0)
Output: [1, 2, 3, 4]
After the function is run, the first array should remain unchanged.
After the function is run, the second array should remain unchanged.
Solution 1:

function frankenSplice(arr1, arr2, n) {
  let localArray = arr2.slice();
  for (let i = 0; i < arr1.length; i++) {
    localArray.splice(n, 0, arr1[i]);
    n++;
  }
  return localArray;
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);

Idea: ① because the title requires "the second array should remain unchanged", use the slice method of array to copy the localArray based on arra2, and use localArray to complete the title requirements;
② Loop through arr1, and insert the elements in arr1 into localArray in turn. The splice method is used here. Note that the title requires "insert in order", so the n coordinate should be incremented.
Knowledge points: two methods of Array = "slice, splice"
Slice(start,end): it is equivalent to a shallow copy of the array and does not change the original array value, [start, end) starts from start and does not include end. If you do not fill in the value, it means all copies, where end is optional. If you only fill in start, it means from start to end,
Splice(start,count,item): deleting or inserting elements will change the original array. Start indicates the start index, count indicates the number of elements to be deleted, if item has a value, it indicates the inserted value (there can be more than one item). If you want to insert elements, count is set to 0.
Horizontal expansion: the method used in step ② of solution 1 is to increase the N coordinate, and another method is to cycle in reverse order, so that n does not need to increase, as shown below:

function frankenSplice(arr1, arr2, n) {
  let localArray = arr2.slice();
  for(let i=arr1.length-1;i>=0;i--){
    localArray.splice(n, 0, arr1[i]);
  }
  return localArray;
}

Solution 2:

function frankenSplice(arr1, arr2, n) {
  let localArr = arr2.slice();
  localArr.splice(n, 0, ...arr1);
  return localArr;
}

Idea: the idea is the same as that of solution 1, except that the loop is replaced by the spread operator and directly inserted into localArr with... arr1.

It will be written later.

Topics: Javascript Algorithm