In the project development, when the interface is called to request data and the list data format returned by the background is not grouped according to a certain control condition, we need to re-process the data ourselves so as to obtain the data structure we want

<script> /** * array * @example arrGroup(array, function) * @param {Array} arr * @param {Function} fn * @returns {Array} [[],[]] */ const list = [{ id: 1, name: "Zhang", the position: "the manager"}, {id: 2, name: "bill", the position: "shareholders"}, {id: 3, name: "king 5", the position: "c"}, {id: 4, name: }, {id: 6, name: "li Bo ", position:" li Bo "}, {id: 6, name: "Li Bo ", position:" Li Bo "}, {id: 6, name: "Li Bo ", position:" Li Bo "}, {id: 6, name: "Li Bo ", position: }] function arrGroup(arr, fn) {const obj = {}; arr.forEach(item => { const key = JSON.stringify(fn(item)); obj[key] = obj[key] || []; obj[key].push(item) }); return Object.keys(obj).map(k => { return obj[k]; }) } const newArr = arrGroup(list, (item) => item.position) console.log(newArr) </script>Copy the code

Running results: