Skip to content

Instantly share code, notes, and snippets.

@oaugusto256
Last active October 31, 2019 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oaugusto256/954bdeaaa197036b09ebfa95354aca9d to your computer and use it in GitHub Desktop.
Save oaugusto256/954bdeaaa197036b09ebfa95354aca9d to your computer and use it in GitHub Desktop.
Array manipulations with JavaScript
// Filter unique array
const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
// Add element in an array at state
addElement = (event) => {
this.setState(state => {
const list = [...list, state.element];
return {
list,
element: '',
};
});
}
// Remove element in an array at state
deleteElement = indexToDelete => {
this.setState(({ list }) => ({
list: list.filter((toDo, index) => index !== indexToDelete)
}));
}
// Transform array of objects with property value to object value
const transformCustomAttributes = customAttributes => 
customAttributes.reduce((ac, cur) => { 
ac[cur.attribute_code] = cur.value; 
return ac; 
}, {});
const transformProperties = products => 
products.map(cur => ({ 
...cur, custom_attributes: transformCustomAttributes(cur.custom_attributes) 
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment