0

I have the solution but Is there any other nicer way to do in javascript or is it possible to modify the arr1 itself and have arr1 as array of objects alone

I have array of objects and string

arr1 = [{
    id: 'id1',
    name: 'name1'
}, {
    id: 'id2',
    name: 'name2'
}, '/roll', '/roll1'];

i would like to have array of objects alone at the end

newarr1 = [{
    id: "id1",
    name: "name1"
}, {
    id: "id2",
    name: "name2"
}]

current solution

arr1.map((item) => {
    if (typeof item === 'object') return newarr1.push(item)
})
1
  • Never use map where you need a forEach. let newArr1 = []; arr1.forEach((item) => { if (typeof item === 'object') newarr1.push(item); }); Commented Feb 10, 2023 at 7:58

2 Answers 2

4
newArr = arr1.filter(item => typeof item === 'object')
Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer:) This is not needed for OP's case, but a good-to-know: arrays are considered objects too, and if OP has nested arrays and wants to include/exclude them, an additional check for Array.isArray(item) is going to help :)
3
const isObject = item => Object.getPrototypeOf(item) === Object.prototype;

const newarr1 = arr1.filter(isObject);

Demo

const isObject = item => Object.getPrototypeOf(item) === Object.prototype;

const arr1 = [{id: 'id1', name: 'name1'}, {id: 'id2', name: 'name2'}, '/roll', '/roll1'];
const newarr1 = arr1.filter(isObject);

console.log(newarr1);

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.