# [Codewars - 7kyu解題] A twisted way to select an element from an array 字母替換成數字 ###### tags: `Codewars`,`7kyu`,`Javascript`,`Array`,`.forEach()`,`.sort()`,`.reverse()`,`.slice()`,`.indexOf()`,`.find()`,`.filter()` > Javascript菜鳥紀錄Codewars解題過程 ## Instructions 題目 :link: https://www.codewars.com/kata/5a1c84c1c374cb6f7e000104 :pushpin: **Instructions:** 接收兩組陣列: arrSearch and arrTake。 將arrSearch中的單字依首字字母,以Z-A的反向順序排序,取出排序後陣列的第三個單字,再取第三個單字的第三個字母。 若取出的字母和arrTake中的單字首字字母相同,回傳比對到的第一個單字,若沒有比對到,則回傳'Nothing here'。 You have two arrays: arrSearch and arrTake. arrSearch has to be sorted in reverse alphabetical order. Now, from arrSearch extract the third element, and from that element select the third letter. If the letter you selected matches the first letter of one or more elements of arrTake, return the first element that starts with the respective letter. If there is no element to match in the second array then return 'Nothing here'. :bulb: **Examples:** ['banana','rose','orange','apple'] Output===>['carrot','nectarines','cucumber','ananas'] ['attack','defense','fight','retreat'] Output===>['fist','punch','break'] ## My Solution 我的解法 ```javascript= function select (arrSearch, arrTake){ var arrS = arrSearch.sort().reverse().slice(2,3); var arrT = [] var S = arrS[0].split('').slice(2,3).toString(); arrTake.forEach(i => arrT.push(i.split('').slice(0,1).toString())); if(arrT.indexOf(S)==-1){ return 'Nothing here'} else{ return arrTake[arrT.indexOf(S)]; } } ``` ## Solutions(1) 其他更精簡的寫法 ```javascript= function select(arrSearch, arrTake) { let char = arrSearch.sort().reverse()[2][2]; return arrTake.find(x => x[0] == char) || 'Nothing here'; } ``` ## Solutions(2) 其他更精簡的寫法 ```javascript= function select(arrSearch, arrTake) { return arrTake.filter(e => e[0] === arrSearch.sort().slice(-3)[0][2] )[0] || 'Nothing here'; } ``` ## Solutions(3) 其他更精簡的寫法 ```javascript= function select (s,t){ let L = s.sort().reverse()[2][2] return t.filter(w=>w[0]==L)[0]||"Nothing here" } ``` ## :memo: 學習筆記 :bulb: **Array.prototype.filter()** https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/filter > 建立一個經指定之函式運算後,由原陣列中通過該函式檢驗之元素所構成的新陣列。 > ```javascript= const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"] ``` --- :bulb: **Array.prototype.find()** https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/find > 回傳第一個滿足所提供之測試函式的元素值。否則回傳 undefined。 > ```javascript= const array1 = [5, 12, 8, 130, 44]; const found = array1.find(element => element > 10); console.log(found); // expected output: 12 ```