如何解决将元素移动到数组的前面:Javascript
我有一组这种格式的对象
let arr = [ { name: "test1",id: 5},{ name: "test2",id: 6 },{ name: "test3",id: 8 } ]
现在我基本上想通过重新排列将带有 6 的项目移动到数组的前面,使结果变为
let result = [ { name: "test2",{ name: "test1",id: 8 } ]
我所尝试的
const found = arr.find((element) => {
return element.id === 6;
});
if (found) {
const [...arr,found] = arr;
return found;
} else {
return arr;
}
解决方法
您可以使用 Array.unshift() 在数组的开头添加元素,使用 Array.splice() 删除数组元素。
let arr = [ { name: "test1",id: 5},{ name: "test2",id: 6 },{ name: "test3",id: 8 } ]
let result = [...arr];
const index = result.findIndex(e => e.id === 6)
result.unshift(result.splice(index,1)[0])
console.log(result);
您可以使用 Array.unshift
和 Array.splice
。
let arr = [{name:"test1",id:5},{name:"test2",id:6},{name:"test3",id:8}]
const moveToFront = (data,matchingId) => {
//find the index of the element in the array
const index = data.findIndex(({id}) => id === matchingId);
if(index !== -1) {
//if the matching element is found,const updatedData = [...data];
//then remove that element and use `unshift`
updatedData.unshift(...updatedData.splice(index,1));
return updatedData;
}
//if the matching element is not found,then return the same array
return data;
}
console.log(moveToFront(arr,6));
.as-console-wrapper {
max-height: 100% !important;
}
您可以使用支票的增量对数组进行排序。
const
array = [{ name: "test1",id: 5 },id: 8 }];
array.sort((a,b) => (b.id === 6) - (a.id === 6));
console.log(array);
const array = [{ name: "test1",id: 8 }];
const sortedArray = array.sort((a,b) => (b.id === 6) - (a.id === 6)); console.log(sortedArray);
讨论了一种按照 Array 对象中每个项目的索引号顺序对 JavaScript Array 进行排序的简单方法。如果您想按字母顺序排序并且不需要使用 String.sort() 之类的函数创建新的字符串数组,这会很有帮助。
如果您想快速解决在 JavaScript 中对数组进行排序的快速解决方案,对您可能有用的快速提示如下。请记住,使用语言中内置的 Array 方法始终是最佳实践。它们旨在快速高效地工作。但是,如果您真的想按索引号对数组进行排序并且没有字符串数组,那么本文将适合您。:
String→Number:当一个函数返回一个 Number 值时,那么 JavaScript 将其解释为等于代码中的 Number 值......该函数通过传递两个参数来使用,当它们相等时应该返回 true 并且当它们不相等时为假。在这种情况下,我们有点反向比较它们。我们正在检查 Array 内项目的 ID 以查看它们是否匹配,但我们减去一个以检查它们是否小于。这是因为当我们调用 .sort() 时,JavaScript 正在按字母顺序排序,值为 6 的 ID 将位于列表的末尾。因此,值 -1 将使其以正确的顺序出现。如果您想对您的数组使用此方法,请在下面添加评论!
,您可以使用 filter
和 unshift
let arr = [{ name: "test1",id: 8 }];
let firstObject;
let result = arr.filter((value) => {
if (value.id != 6) return value;
firstObject = value;
});
result.unshift(firstObject);
console.log(result);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。