JavaScript - get array element fulfilling a condition

Viewed 144878

I'm learning JavaScript using W3C and I didn't find an answer to this question.

I'm trying to make some manipulations on array elements which fulfill some condition.

Is there a way to do it other than running on the array elements in for loop? Maybe something like (in other languages):

foreach (object t in tArray)
   if (t follows some condition...) t++;

another thing, sometimes I want to use the element's value and sometimes I want to use it as a reference. what is the syntactical difference?

As well, I'll be happy for recommendations on more extensive sites to learn JavaScript from. thanks

10 Answers

You can use Array.prototype.find, wich does exactly what you want, returns the first element fullfilling the condition. Example:

> ([4, {a:7}, 7, {a:5, k:'r'}, 8]).find(o => o.a == 5)

{a:5, k:'r'}

Write a generic function that accepts various conditions:

function array_only(arr, condition) {
    hold_test=[]
    arr.map(function(e, i) {if(eval(condition)){hold_test.push(e)}})
    return(hold_test)
    }

Example:

use_array = ['hello', 'go_there', 'now', 'go_here', 'hello.png', 'gogo.log', 'hoho.png']

Usage:

return only elements containing .log extension:

array_only(use_array, "e.includes('.log')")

[ 'gogo.log' ]

return only elements containing .png extension:

array_only(use_array, "e.includes('.png')")

[ 'hello.png', 'hoho.png' ]

return only elements NOT containing .png extension:

array_only(use_array, "!e.includes('.png')")

[ 'hello', 'go_there', 'now', 'go_here', 'gogo.log' ]

return elements containing set of extensions and prefixes:

array_only(use_array, "['go_', '.png', '.log'].some(el => e.includes(el))")

[ 'go_there', 'go_here', 'hello.png', 'gogo.log', 'hoho.png' ]

You can easily pass MULTIPLE CONDITIONS

return all png files that are less than 9 characters long:

array_only(use_array, "e.includes('.png') && e.length<9")

[ 'hoho.png' ]

I am joining in late, but I have an interesting solution. If you only want to filter a single element i.e the first element that satisfies the condition, you could use the JS find function.

myArray.find(x => x > 5)

Problem:

I need to know if a client set exists for any PJ client.

Solution:

function deveExibirLista(lst: Clientes[]){
    return lst.some(cli => cli.Documento === 14);
}

It's return boolean

Related