LoginSignup
1
3

More than 5 years have passed since last update.

JavaScriptの文字列から配列、オブジェクトから配列、配列の再構築のあれこれ

Last updated at Posted at 2019-03-07

個人的によく使うのでメモがてら公開。

2次配列を1次配列に統合

const array = [
    1, [2, 3, 4], 5
]
const flattened = array.reduce(
    (accumulator, currentValue) => accumulator.concat(currentValue),
    []
)
console
[ 1, 2, 3, 4, 5 ]

文字列から配列

let array2 = "テキスト1,テキスト2,テキスト3,テキスト4"
array2 = array2.split(',')
console
[ 'テキスト1', 'テキスト2', 'テキスト3', 'テキスト4' ]

配列の中にあるオブジェクトの値の文字列を配列化

const array3 = [
    { names: "テキスト1,テキスト2,テキスト3,テキスト4" },
    { names: "テキスト1,テキスト2,テキスト3" },
    { names: "" }
]
const values = array3.map((contact, index) => {
    return contact.names.split(',')
})
console
[
  [ 'テキスト1', 'テキスト2', 'テキスト3', 'テキスト4' ],
  [ 'テキスト1', 'テキスト2', 'テキスト3' ],
  [ '' ]
]

2次配列を1次配列にして空白の配列を削除

const array3 = [
    { names: "テキスト1,テキスト2,テキスト3,テキスト4" },
    { names: "テキスト1,テキスト2,テキスト3" },
    { names: "" }
]
const values = array3.map((contact, index) => {
    return contact.names.split(',')
})
// 2次配列を1次配列に
let flattened2 = values.reduce(
    (accumulator, currentValue) => accumulator.concat(currentValue),
    []
)
// 空の要素を消す
flattened2 = flattened2.filter(function (x) {
    return !(x === null || x === undefined || x === "")
})
console
[ 'テキスト1', 'テキスト2', 'テキスト3', 'テキスト4', 'テキスト1', 'テキスト2', 'テキスト3' ]

同じ文字列を数えて一つに絞りオブジェクトに変換

const array3 = [
    { names: "テキスト1,テキスト2,テキスト3,テキスト4" },
    { names: "テキスト1,テキスト2,テキスト3" },
    { names: "" }
]
const values = array3.map((contact, index) => {
    return contact.names.split(',')
})
let flattened2 = values.reduce(
    (accumulator, currentValue) => accumulator.concat(currentValue),
    []
)
flattened2 = flattened2.filter(function (x) {
    return !(x === null || x === undefined || x === "")
})
// ここから
let counts = {}
for (var i = 0; i < flattened2.filter(v => v).length; i++) {
    var key = flattened2[i]
    counts[key] = (counts[key]) ? counts[key] + 1 : 1;
}
const local = Object.keys(counts).map((contact, i) => {
    return { id: i, value: contact, count: counts[contact] }
}, counts)
console
[
  { id: 0, value: 'テキスト1', count: 2 },
  { id: 1, value: 'テキスト2', count: 2 },
  { id: 2, value: 'テキスト3', count: 2 },
  { id: 3, value: 'テキスト4', count: 1 }
]

まとめ

ES2019のflat(),flatMap()早く使いたい。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3