Sort a String of Comma-Separated Items Alphabetically

How to alphabetically sort of a string delimited by commas and sort alphabetically by members last name?

Your logic can be simplified, as sorted has a key argument:

res = sorted(students.split(','), key=lambda x: x.split()[1])

['Jane Bee janebee@gmail.com 555-555-5555',
'John Dee johndee@gmail.com 555-555-5555',
'Sarah Zee sarahzee@gmail.com 555-555-5555']

Note that str.split defaults to whitespace, so str.split(' ') is not required. In addition, str.split returns a list object, so there's no need to manually iterate and append.

Sort a string of comma-separated items alphabetically


x = c("a, b, c, d", "d, a, b, c", "b, a, c, d")
y = unname(sapply(x, function(x) {
paste(sort(trimws(strsplit(x[1], ',')[[1]])), collapse=',')} ))
y

[1] "a,b,c,d" "a,b,c,d" "a,b,c,d"

trimws() removes whitespace so sort works correctly on the splitted string. sort() sorts alphabetically. paste(..., collapse = ',') concatenates the sorted vector of strings into a single string.

Sort comma separated list Alphabetically PHP

I am pasting you a snippet what it is doing:

  1. Splicing string
  2. Remove blank spaces on each element
  3. Remove empty elements
  4. Sorting array
  5. Printing the result

I hope it is usefull for you

<?php
$xyz = "Europe, France, Italy, Spain, UK, US,Nordic, West Europe, Belgium, Luxembourg, Netherlands, Sweden,US,Asia, Europe, Israel, North America, India,North America, , China, Hong Kong,West North Central, West South Central,UK,East South Central,Middle Atlantic, Greater China, Malaysia, Singapore, Taiwan, Middle Atlantic, Global, Australasia, Central and East Europe";
$array = array_filter(array_map('trim', explode(',', $xyz)));
asort($array);
$array = implode(', ', $array);
print_r($array);

How to sort a string in R that contains comma separated numbers

In tidyverse, we can use separate_rows while converting the type to split the 'a' by the delimiter, then arrange the 'b', 'a', columns, grouped by 'b', paste the elements of 'a' in a new column and bind it with the original dataset

library(dplyr)
library(tidyr)
data_frame %>%
# // split a by the delimiter and expand the rows
separate_rows(a, convert = TRUE) %>%
# // order the columns
arrange(b, a) %>%
# // grouped by b
group_by(b) %>%
# paste the elements of a
# toString => paste(..., collapse=", ")
summarise(c = toString(a)) %>%
# // select the column c
select(c) %>%
# // bind with the original dataset
bind_cols(data_frame, .)
# A tibble: 2 x 3
# a b c
# <chr> <chr> <chr>
#1 2,29,3,30,31,4,5,2,28,29,3,30,4,5 x 2, 2, 3, 3, 4, 4, 5, 5, 28, 29, 29, 30, 30, 31
#2 12,13,14,15,18,19,20,12,13,14,15,18,19,20,21 y 12, 12, 13, 13, 14, 14, 15, 15, 18, 18, 19, 19, 20, 20, 21

Or using strsplit with map. We split the string 'a' with ,, loop over the list with map, convert to numeric, sort and then paste it to a single string

library(purrr)
data_frame %>%
mutate(c = map_chr(strsplit(a, ","), ~
toString(sort(as.numeric(.x)))))
# A tibble: 2 x 3
# a b c
# <chr> <chr> <chr>
#1 2,29,3,30,31,4,5,2,28,29,3,30,4,5 x 2, 2, 3, 3, 4, 4, 5, 5, 28, 29, 29, 30, 30, 31
#2 12,13,14,15,18,19,20,12,13,14,15,18,19,20,21 y 12, 12, 13, 13, 14, 14, 15, 15, 18, 18, 19, 19, 20, 20, 21

sort value seperated by comma

Split sort and combine the string.

split_and_sort <- function(x) {
toString(sort(unlist(strsplit(x, ',\\s*'))))
}

split_and_sort(a)
#[1] "AB, MN, OP"

split_and_sort(b)
#[1] "A B, MN, O P"

To apply it on column you can use sapply -

split_and_sort <- function(x) {
sapply(strsplit(x, ',\\s*'), function(x) toString(sort(x)))
}

df$a <- split_and_sort(df$a)

Sort strings/words alphabetically separated by comma within a column in SQL (entire column)

Here is an Oracle solution using Common Table Expressions (CTEs) to break the problem down. Not sure if this will help, but maybe it will give you an idea or a starting point that you can apply to your environment.

SQL> -- Set up original data set
SQL> with bird_tbl(id, unsorted_list) as (
select 1, 'Sparrow, Eagle, Crow' from dual union all
select 2, 'Woodpecker, Sparrow' from dual union all
select 3, 'Crow, Eagle' from dual
),
-- Split the list into a row for each element
split_tbl(id, bird) as (
select id, regexp_substr(unsorted_list, '(.*?)(, |$)', 1, level, null, 1)
from bird_tbl
connect by level <= regexp_count(unsorted_list, ', ')+1
and prior id = id
and prior sys_guid() is not null
)
-- select * from split_tbl;
-- Rebuild the sorted row
select id, listagg(bird, ', ')
within group (order by bird) sorted_list
from split_tbl
group by id;

ID SORTED_LIST
---------- --------------------
1 Crow, Eagle, Sparrow
2 Sparrow, Woodpecker
3 Crow, Eagle

EDIT: Here's how to apply to your situation. Just replace <your_primary_key> with the primary key column name, <your_column_name> with the name of the column that contains the unsorted list and <your_table_name> with the name of the table.

with split_tbl(<your_primary_key>, <your_column_name>) as (
select <your_primary_key>, regexp_substr(<your_column_name>, '(.*?)(, |$)', 1, level, null, 1)
from <your_table_name>
connect by level <= regexp_count(<your_column_name>, ', ')+1
and prior <your_primary_key> = <your_primary_key>
and prior sys_guid() is not null
)
-- select * from split_tbl;
-- Rebuild the sorted row
select <your_primary_key>, listagg(<your_column_name>, ', ')
within group (order by <your_column_name>) sorted_list
from split_tbl
group by <your_primary_key>;

Sort ArrayList alphabetically by value after a comma in each String


import java.util.*;

public class Test {
public static void main(String... args) {
List<String> list = new ArrayList<>();
list.add("zzz, abc");
list.add("yy, ghi");
list.add("x, def");
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return filter(lhs).compareTo(filter(rhs));
}

private String filter(String s) {
// consider the first comma
return s.replaceFirst("^.*?, ", "");
// to consider the last comma instead:
// return s.replaceFirst("^.*, ", "");
}
});
for (String s : list)
System.out.println(s);
}
}

The output is:

zzz, abc
x, def
yy, ghi

javascript how to sort strings containing comma separated values


str.split(",").sort().join(",")

Alphabetically order a field with comma separated values

This would be so much easier with a properly normalized data model.

To get a sorted string, you need to first unnest the elements and then aggregate them back into a sorted string.

select other_columns
(select string_agg(country, ',' order by country)
from unnest(string_to_array(countries, ',')) as t(country)
) as countries_sorted
from the_table

You can put that into a function to make your life easier:

create function sort_csv_value(p_input text)
returns text
as
$$
select string_agg(word, ',' order by word)
from unnest(string_to_array(p_input, ','));
$$
language sql
immutable;

Then you can use it like this:

select other_columns
sort_csv_value(countries) as countries_sorted
from the_table


Related Topics



Leave a reply



Submit