Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to restructure an array of strings based on prefix

Andrey Gershun edited this pageJan 20, 2016 ·2 revisions

#How to restructure an array of strings based on prefix?

Source:StackOverflow

Question

I have an array containing a list of filenames:

varfiles=['home_01.ai','home_02.ai','home_03.ai','imprint_01.ai','imprint_02.ai']

What I want to do is reorganise this array into a multi-dimensional array that groups together each file with the same prefix. In this case:

varfirstArray=['home_01.ai','home_02.ai','home_03.ai'],/*home*/secondArray=['imprint_01.ai','imprint_02.ai'];/*imprint*/

How could I achieve that when there can be a variable amount of prefixes that can be any length in my file array?

Answer

You can do it with AlaSQL JavaScript data processing library.

Here is the solution for your problem:

varres=alasql('COLUMN OF SELECT ARRAY(_) FROM ? \         GROUP BY _->split("_")->0',[files]);

This statement returns array of arrays grouped by prefix:

    [ [ 'home_01.ai', 'home_02.ai', 'home_03.ai' ],      [ 'imprint_01.ai', 'imprint_02.ai' ] ]

Here:

  • COLUMN OF - return only first column of query
  • SELECT ... FROM ? GROUP BY ... - select statement
  • ARRAY(_) - group records in array
  • FROM ? - query from parameter [files]
  • GROUP BY->split("")->0 - take a value, split it with '' and then take first element of array (similar to JS r.split('')[0]

© 2014-2026,Andrey Gershun &Mathias Rangel Wulff

Please help improve the documentation by opening a PR on thewiki repo

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp