mathieubeauregard
3/15/2018 - 3:45 PM

Sort array of objects, by object property

Sort array of objects, by object property

/**
 * Sort array of objects, by object property
 * 
 * @param  {Array}  targetArray 	Array to sort
 * @param  {String} key         	Object key, used to sort array
 * @return {Array}             		Sorted array
 */
function sortArrayBy(targetArray = [], key = '') {
	targetArray.sort((oObjA, oObjB) => {
		let iRes = 0
		
		if (oObjA[key] < oObjB[key]) {
			iRes = -1
		} else if (oObjA[key] > oObjB[key]) {
			iRes = 1
		}

		return iRes
	})

	return targetArray
}

export {sortArrayBy as default}