JavaScript Array Methods: find, map, reduce, splice, filter, and some Usage Guide
JavaScript Array Methods: find, map, reduce, splice, filter, and some Usage Guide
find Method
The find method locates elements within an array and can modify the original array. For instance, when searching by identifier and assigning to a target variable:
let targetNodeData = reactive<NodeData>()
targetNodeData = nodeList.value.find((element) => element.identifier == props.nodeId).details
When modifying properties within targetNodeData, the source array nodeList.value will also reflect these changes:
targetNodeData.nodeDetails.content[currentSection.value].push({
field: '',
content: '',
})
To prevent modifications from affecting the original array, use deep cloning with JSON.parse(JSON.stringify(item)).
map Method
Creates a new array by executing a function for each element. When returning objects, wrap them in parentheses to avoid syntax errors:
- For object returns:
collection.map(key => ({})) - For value transformations:
collection.map(key => key * 2) - Converting Objects to Arrays:
transformedData = Object.keys(sourceData).map(propertyKey => ({
property: propertyKey,
content: sourceData[propertyKey]
}))
reduce Method
Iterates through array elements, accumulating results from previous operations. Useful for transforming arrays into objects:
let items = [{property:'title',content:'John'},{property:'years',content:25}]
items = items.reduce((accumulator,currentItem) => {
accumulator[currentItem.property] = currentItem.content
return accumulator
},{}) // Initial empty object is required
console.log('items',items) // Result: { title: "John", years: 25 }
filter Method
Filters elements based on specified conditions, creating a shalloww copy without affecting the original array:
const filteredReferences = computed(() => {
return InputParameters.filter((element) => element.property === 'reference')
})
splice Method
Directly modifies the original array:
- Insert elements:
collection.splice(position,0,newValue)- second paramter0indicates insertion - Remove elements:
collection.splice(position,1)- removes one element at specified position
some Method
Checks if at least one element meets specific criteria, returning a boolean value:
// Check if array contains element with property 'agentConfirmation'
collection.some((element) => element.property === 'agentConfirmation')
Method Comparison and Use Cases
Element Retrieval:
filter: Returns all elements meeting criteriafind: Returns first matching elementfindIndex: Returns index of first matching elementsome: Returns boolean indicating existence
Element Modification:
splice: Handles element insertion and deletionmap: Transforms element valuesreduce: Performs aggregations; transforms arrays to objects