Sophia
Sophia

Reputation: 43

How can I exclude data containing certain characters from an array in JavaScript?

How can I exclude data containing certain characters from an array in JavaScript.

I want to exclude titles with specific strings. Strings are not multiple patterns. One.

For example, I have an array.

sample Array

[
    {
        "title": "aaa",
        "url": "https://aaa.com"
    },
    {
        "title": "bbb",
        "url": "https://bbb.com"
    },
        {
        "title": "ccc",
        "url": "https://ccc.com"
    },
]

I want to get an array like below.(exclude title: bbb)


[
    {
        "title": "aaa",
        "url": "https://aaa.com"
    },
    {
        "title": "ccc",
        "url": "https://ccc.com"
    },
]

Upvotes: 0

Views: 233

Answers (2)

gpbaculio
gpbaculio

Reputation: 5968

use Array filter: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

from docs:

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

in your case

const result = yourArray.filter(o => o.title !== 'bbb')

Upvotes: 2

Kiddo
Kiddo

Reputation: 139

Use filter method.

let arr = [
    {
        "title": "aaa",
        "url": "https://aaa.com"
    },
    {
        "title": "bbb",
        "url": "https://bbb.com"
    },
        {
        "title": "ccc",
        "url": "https://ccc.com"
    },
]


let newArr = arr.filter(obj => obj.title !== "bbb")

console.log(newArr)

Upvotes: 2

Related Questions