1

I want to build certain UI, it involves manipulation of array object, I know the pseudo code, but I don't know how to produce the output. Below is my case statement. Need guidance.

if outer date is in between of data's date_from and date_to

[{
  date:'2017-05-11',
  data:[{id: 2, name: 'abc', date_from:'2017-05-03', date_to:'2017-05-05'}]
}]

set type to mid

[{
  date:'2017-05-11',
  data:[{id: 2, name: 'abc', date_from:'2017-05-03', date_to:'2017-05-05', type:'mid'}]
}]

if outer date is equal to date_from

[{
  date:'2017-05-11',
  data:[{id: 2, name: 'abc', date_from:'2017-05-11', date_to:'2017-05-15'}]
}]

set type to is_start_left

if outer date is equal to date_to

[{
  date:'2017-05-11',
  data:[{id: 2, name: 'abc', date_from:'2017-05-01', date_to:'2017-05-11'}]
}]

set type to is_end_right

1 Answer 1

1

You could use a nested conditional (ternary) Operator ?: and check date_from, or date_to or return just 'mid'.

function setType(array) {
    array.forEach(a => a.data.forEach(o => o.type = a.date === o.date_from ?
        'is_start_left' :
        a.date === o.date_to ?
            'is_end_right' :
            'mid'
    ));
    return array;
}

console.log(setType([{ date: '2017-05-11', data: [{ id: 2, name: 'abc', date_from: '2017-05-03', date_to: '2017-05-05' }] }]));
console.log(setType([{ date: '2017-05-11', data: [{ id: 2, name: 'abc', date_from: '2017-05-11', date_to: '2017-05-15' }] }]));
console.log(setType([{ date: '2017-05-11', data: [{ id: 2, name: 'abc', date_from: '2017-05-01', date_to: '2017-05-11' }] }]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

2 Comments

oh i see forEach within forEach. but i didn't know ternary operator can do multiple else.
@AlanJenshen, from this snippet, i hardly can tell where the error is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.