-3

I have this array

[[11,12,13,14],[21,22,23,24],[31,32,33,34],[41],[43],[51]]

,

expected output like this: 11-14,21-24,31-34,41,43,51

3
  • Do you just want to output as this format? Commented Nov 21, 2022 at 9:03
  • What have you tried so far ? Commented Nov 21, 2022 at 9:04
  • If the length of the nested array is 1, return array[0]. Otherwise, concatenate the first and last elements with - between them. Commented Nov 21, 2022 at 9:05

3 Answers 3

0

We can do it via Array.map()

const data = [[11,12,13,14],[21,22,23,24],[31,32,33,34],[41],[43],[51]]

let result = data.map(d => {
   if(d.length < 2){
     return d[0]
   }
   return d.at(0) +' -' + d.at(-1)
})
console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

0
[[11,12,13,14],[21,22,23,24],[31,32,33,34],[41],[43],[51]].map((arr) => {
  if(arr.length > 1){
     return `${arr[0]}-${arr[arr.length-1]}`
  }
  return `${arr[0]}`;
})

['11-14', '21-24', '31-34', '41', '43', '51']

Comments

0

You can use Array.prototype.reduce():

const data = [[11,12,13,14],[21,22,23,24],[31,32,33,34],[41],[43],[51]]
const result = data.reduce(
  (a, arr) => [...a, arr.length >= 2 ? `${arr[0]}-${arr[arr.length - 1]}` : arr[0]], 
  []
)

console.log(result)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.