0

I have such method:

  function sort(arr) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].title !== 'Test') {
        arr[i] = {
          ...arr[i],
          data: sortByType(arr[i].data),
          full: sortByType(arr[i].full)
        };
      }
    }

    return arr;
  }

Can it be simplified to use filter or foreach?

1
  • Please show inputs and expected outputs so that answerers can ensure their functions work as expected. Please also show what you've tried so far, and any research you've done. Commented May 22, 2020 at 13:08

3 Answers 3

2

I have done it with map:

I havent tested it, but should work like you original code

function sort(arr) {
   return arr.map(el => {
      if(el.title === "Test") return el;
      return { ...el, data: sortByType(el.data), full: sortByType(el.full) }
   })
}
Sign up to request clarification or add additional context in comments.

Comments

1

I think that your loop is the simplest right now.

Image you want to switch it to using a map, your code will become:

function sort(arr) {
    return arr.map(elem => {
      // you now need to handle this case too
      if (elem.title === "Test") 
        return elem;

      return { 
        ...elem, 
        data: sortByType(elem.data), 
        full: sortByType(elem.full) 
      }
    });
}

Which is essentially more code, and I don't think you gain anything from it imho.

A filter won't work in your case though.

Comments

0

this should help

function sort(arr) {
    return arr.map((item) =>{
        if(item.title != "Test") {
            item = {
                ...item, 
                data: sortByType(item.data),
                full: sortByType(item.full)
            }
        }
        return item;
    })
}

Comments

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.