-6

I want to get the array from:

const foo = [
    FOO_BAR_A_READ_SELF,
    FOO_BAR_A_WRITE_SELF,
    FOO_BAR_A,
    FOO_BAR_A_READ_ALL,
    FOO_BAR_A_WRITE_ALL,
    FOO_BAR_B_READ_SELF,
    FOO_BAR_B_WRITE_SELF,
    FOO_BAR_B,
    FOO_BAR_B_READ_ALL,
    FOO_BAR_B_WRITE_ALL
]

to

const foo = [
    FOO_BAR_A,
    FOO_BAR_A_READ_SELF,
    FOO_BAR_A_WRITE_SELF,
    FOO_BAR_A_READ_ALL,
    FOO_BAR_A_WRITE_ALL,
    FOO_BAR_B,
    FOO_BAR_B_READ_SELF,
    FOO_BAR_B_WRITE_SELF,
    FOO_BAR_B_READ_ALL,
    FOO_BAR_B_WRITE_ALL
]

i tried to go with the length by splitting with the "_", but I never worked with the sort function that specific.

I only used desc and asc ( return 1 > -1 ) || ( return -1 > 1 )

Can someone can explain me how I can get the wanted result?

Daniel
  • 87
  • 9
  • 1
    Your code is not valid Javascript. Strings need delimiters, and array items need to be separated with commas. – CertainPerformance Jun 23 '19 at 22:32
  • Your problem with the given input/output can have multiple solutions, you didn't mention how do you want to compare strings? based on what? length? something else? – Ammar Jun 23 '19 at 22:37
  • You should edit the question to add the logic of the sort. It looks like you want to sort be the part after `BAR` in alphabetical order and then the `READ` and `WRITE` of `SELF` followed the same for `ALL` but you're making us guess by not being explicit. – Mark Jun 23 '19 at 22:52

2 Answers2

0

Not sure it was my best...

var arr = [
    'FOO_BAR_A_WRITE_SELF',
    'FOO_BAR_A',
    'FOO_BAR_A_READ_SELF',
    'FOO_BAR_A_READ_ALL',
    'FOO_BAR_A_WRITE_ALL',
    'FOO_BAR_B_READ_SELF',
    'FOO_BAR_B_WRITE_SELF',
    'FOO_BAR_B',
    'FOO_BAR_B_READ_ALL',
    'FOO_BAR_B_WRITE_ALL'
];

const onRWorder=s=>{
  let x = s.replace('_WRITE_','_')
  if (x != s) x += '_WRITE'
  else {
    x = s.replace('_READ_','_')
    if (x!= s) x += '_READ'
  }
  return x
}

arr.sort(function(a, b){
  let a1 = onRWorder(a)
  let b1 = onRWorder(b)
  if(a1 < b1) { return -1 }
  if(a1 > b1) { return 1 }
  return 0
})

for (let z of arr) console.log(z)
.as-console-wrapper { max-height: 100% !important }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
-1

did you try this ?

var arr = [
    'FOO_BAR_A_WRITE_SELF',
    'FOO_BAR_A',
    'FOO_BAR_A_READ_SELF',
    'FOO_BAR_A_READ_ALL',
    'FOO_BAR_A_WRITE_ALL',
    'FOO_BAR_B_READ_SELF',
    'FOO_BAR_B_WRITE_SELF',
    'FOO_BAR_B',
    'FOO_BAR_B_READ_ALL',
    'FOO_BAR_B_WRITE_ALL'
];
var sorted = arr.sort();
console.log(sorted);