Find a value in an array of objects in Javascript
You can loop over the array and test for that property:
function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
var resultObject = search("string 1", array);
How to search for a specific value in an array of objects based on another value [JavaScript]?
To find the element
const arr = arr.find(p => p.property == someValue);
This will return undefined if the element is not found and return the element if found.
To find the index of the element
If you only want the index use findIdex
const index = arr.findIndex(p => p.property == someValue);
If the element is not found it will return -1
and if found return the index.
To check if the element is present i.e bool value
Your current implementation does that. You can simply return that.
return posts.some(e => e.Permission === true && e.Id == PostId)
Seems like you are confusing with how to use the value from somewhere else to search in the array, you can always pass in a callback and check that.
value => value.somProp == value1 && value.otherProp == value2 || someOtherChek(value)
Find the value inside the array of objects that include children from the array of objects
Because you have a nested structure, you can't use .filter
to get all nested objects - .filter
will only return to you the matching objects on the topmost level. Instead, define an empty array on the initial call, then push
to that array when an item passes the test, and pass the array around to each recursive call. Finally, return that array:
var array=[{id:1,value:'value',children:null},{id:2,value:'my value',children:[{id:'child1',value:'my value',children:null},{id:'child2',value:'value',children:null},{id:'child3',value:'value',children:[{id:'childchild1',value:'my value',children:null}]}]},{id:3,value:'value',children:null},{id:4,value:'my value'}];
function find(searchData, target, accum=[]){
target.forEach((f)=>{
if(f.children){
find(searchData, f.children, accum)
}
if(f.value.includes(searchData)){
accum.push(f);
}
});
return accum;
}
console.log(find('my', array));
JAVA: Finding Values in an Array
for(i = 0; i < NUM_VALS; ++i) {
if(userValues[i] == matchValue) {
//numMatches = i; //WRONG
numMatches++; //Correct
}
}
This block is incorrect, you are assigning numMatches to the index value of the array rather, it should have been that if there's a match increment values of numMatches by 1.
Javascript search an array for a value starting with a certain value
You can use the find()
function which allows you to pass a custom function in parameter that will be tested on each value. This way you can use startsWith()
on each value of the array as you intended to do.
Example:
const array1 = ['abc','xyz'];
function findStartWith(arg) {
return array1.find(value => {
return arg.startsWith(value);
});
}
console.log(findStartWith("hello")); // undefined
console.log(findStartWith("abcd")); // abc
console.log(findStartWith("xyzz")); // xyz
Can I update an array of objects by modifiying a value return by array.find()?
Find
just finds the first element in the array, they do not edit the element, but find the element. So when you have the element, you can edit afterward, but you do not have the index of the element inside the array, so you will need the index too if you want to pass the edited element in the array.
You have multiple ways to update. If you want a shorter way, right now it came into my mind like this :
setArray((oldState) =>
oldState.map((item) => {
if (item.value === "one") {
return {
value: "asdasd"
};
}
return {...item};
})
);
So directly you can set the value inside setArray
why? because the map returns a new array.
Or you can write more readable :
const newState = array.map((item) => {
if (item.value === "one") {
return {
value: "asdasd"
};
}
return {...item};
});
setArray(newState)
A similar question can be found here
If you have any questions ask. Thanks.
How to find the array index with a value?
You can use indexOf
:
var imageList = [100,200,300,400,500];
var index = imageList.indexOf(200); // 1
You will get -1 if it cannot find a value in the array.
Find Value in Nested Array
You have to use a different method based on the value
property type, if the value is an array then use Array#some
method to achieve the result.
let res = fruits.find(({ value }) => Array.isArray(value) ? value.some(({ val }) => val === snacks) : value === snacks) || fruits[0]
const snacks = "strawberry";
const fruits = [{
label: "yellowFruit",
value: "banana"
},
{
label: "purpleFruit",
value: "grape"
},
{
label: "redFruit",
value: [{
val: "apple"
},
{
val: "strawberry"
}
]
},
{
label: "greenFruit",
value: "waltermelon"
},
];
let res = fruits.find(({ value }) => Array.isArray(value) ? value.some(({ val }) => val === snacks) : value === snacks) || fruits[0]
console.log(res);
Find value and index of Javascript array element when the index meets another condition
Another solution to this is using reduce() over the arra1
:
const arr1 = [0,1,1,0,1];
const arr2 = ["a","b","c","d","e"];
let res = arr1.reduce(
(acc, v, idx) => v ? acc.concat({val: arr2[idx], idx}) : acc,
[]
);
console.log(res);
Related Topics
Heroku: Running Imagemagick with Paperclip
Converting Upper-Case String into Title-Case Using Ruby
How to Remove All Non - Ascii Characters from a String in Ruby
Include Params/Request Information in Rails Logger
How to Save Settings as a Hash in a External File
How to Reference Global Variables and Class Variables
Tzinfo-Data Present But Not Seen
Bcrypt Error: Devise Ruby 2.0 and Rails 4.0
How to Add Custom Filter to Active Admin
Convert String with Hex Ascii Codes to Characters
Rails: Money Gem Converts All Amounts to Zero
Can't Install Ruby-Debug-Base19X Gem
What Is Catch and Throw Used for in Ruby
How to Check If a Param Is True or False