I've been saving these posts for a while now. I would always want to post something that I myself understand as well. Well Today we have a problem that needs us to flatten a nested array. We should also account for different levels of nesting.
functionsteamrollArray(arr){letnewArr=[]// Loop over array contentsfor(leti=0;i<arr.length;i++){if(Array.isArray(arr[i])){// Recursively flatten entries that are arrays// and push into the newArrnewArr.push(...steamrollArray(arr[i]));}else{// Copy contents that are not arraysnewArr.push(arr[i]);}}returnnewArr;}// or we could do it this way // function nestedArr(arr) {// let newArr = []// for (let i = 0; i < arr.length; i++) {// if (Array.isArray(arr[i])) { // wants to check each element if it is an Array or not.// newArr = newArr.concat(nestedArr(arr[i])) // we're using recursion because we don't know how many levels it will be so we want it to call itself whenever it is needed. call for each array, if it is we go deeper in the nested levels// } else {// newArr.push(arr[i]) // if it is not an array (base case)// }// }// return newArr;// }// console.log(nestedArr([1, [2], [3, [[4]]]])); will display [1, // 2, 3, 4] console.log(steamrollArray([1,[2],[3,[[4]]]]));// will display [1, 2, 3, 4]
Binary Code
In this following post we must return an English translated sentence of the passed binary string.
functionbinaryCode(str){returnstr.split("").map(dataPoint=>{letcharacterPoint=parseInt(dataPoint,2);letdecipheredLetter=String.fromCharCode(characterPoint);returndecipheredLetter;}).join("")}// 2 Binary numeral system Used internally by nearly all // computers, is base 2. The two digits are "0" and "1", expressed // from switches displaying OFF and ON, respectively.// The map() method creates a new array populated with the results // of calling a provided function on every element in the calling // array.// Ex: // const array1 = [1, 4, 9, 16];// // pass a function to map// const map1 = array1.map(x => x * 2);// console.log(map1);// // expected output: Array [2, 8, 18, 32];// we could also do it this way // function binaryAgent(str) {// return str.split(" ").map(elem => String.fromCharCode(parseInt(elem, 2))).join("") // we're converting it into an integer but it will be the ASC code of a character. parseInt is used. the code for binary is 2. fromCharCode makes it convert to the letter we're looking for . Ex "01000001" gets us A, we have an array which we used map to iterate through them. // }console.log(binaryCode("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"));willdisplayAren't bonfires fun!?
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)