---
# System prepended metadata

title: '[Codewars - 7kyu解題] Homogenous arrays 同質陣列'
tags: [Javascript, .filter(), .every(), 7kyu, Codewars, Array, typeof]

---

# [Codewars - 7kyu解題] Homogenous arrays 同質陣列

###### tags: `Codewars`,`7kyu`,`Javascript`,`Array`,`.filter()`,`.every()`,`typeof`

> Javascript菜鳥紀錄Codewars解題過程

## Instructions 題目
:link: https://www.codewars.com/kata/57ef016a7b45ef647a00002d

:pushpin: **Instructions:** 
回傳非空陣列且元素類別同性質的陣列
Given a two-dimensional array, return a new array which carries over only those arrays from the original, which were not empty and whose items are all of the same type (i.e. homogenous). For simplicity, the arrays inside the array will only contain characters and integers.

:bulb: **Examples:** 

Given [[1, 5, 4], ['a', 3, 5], ['b'], [], ['1', 2, 3]], your function should return [[1, 5, 4], ['b']].

:bulb: **Points:**
在此題中，空陣列被預設為非同質陣列。
回傳的陣列內元素必須維持最初的排序。
Please keep in mind that for this kata, we assume that empty arrays are not homogenous.

The resultant arrays should be in the order they were originally in and should not have its values changed.

No implicit type casting is allowed. A subarray [1, '2'] would be considered illegal and should be filtered out.



## My Solution 我的解法
試圖用for-loop和if判斷式土法煉鋼，但語法有誤無法過關...
暫時找不出錯誤的原因，無法修正，先參考[其他寫法](#Solutions-%E5%85%B6%E4%BB%96%E6%9B%B4%E7%B2%BE%E7%B0%A1%E7%9A%84%E5%AF%AB%E6%B3%95)。

```javascript=
function filterHomogenous(arrays) {
  var arr = []
  var res = []
  var jud = ""
  for(let i=0;i<arrays.length;i++){
    for(let j=0;j<arrays[i].length;j++){
        arr.push("'"+typeof arrays[i][j]+"'");
    }
        jud = arr.join("===");
        if(jud){res.push(arrays[i])}
        arr = []
  }
  return res;
}
```









## Solutions 其他更精簡的寫法
```javascript=
function filterHomogenous(arr) {
  return arr.filter(subArr => subArr.length > 0 && subArr.every(val => typeof val === typeof subArr[0]));
}
```


## :memo: 學習筆記

:bulb: **Array.prototype.filter()**
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
> 
> 建立一個經指定之函式運算後，由原陣列中通過該函式檢驗之元素所構成的新陣列。

---
:bulb: **Array.prototype.every()**
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/every
> 
> 測試陣列中的所有元素是否都通過了由給定之函式所實作的測試。

---

:bulb: **typeof**
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Operators/typeof



