前段js-把数组指定元素放在第一位

假如我们有个已知数组 arr
var arr = [1,2,3,4]
var key = 3
我们要根据key的值来找到这个元素,然后把它挪到数组的第一位,让它返回的结果为[3,1,2,4]
for (var i = 0; i < arr.length; i++) {
if (arr[i] === key) {
arr.splice(i, 1);
break;
}
}
arr.unshift(key);
2、数组中是对象,例如把是单据编号的置顶;

 var dataArr = {"state":200,"request":null,"message":"","cause":"","variables":{},"data":[{"changeTime":"2019-12-21 11:20:09.0","changeAfter":"K","contractName":"客商类型","changeBefore":"D"},{"changeTime":"2019-12-21 11:20:09.0","changeAfter":"弋华蕾","contractName":"制单人姓名","changeBefore":"弋华"},{"changeTime":"2019-12-21 11:20:09.0","changeAfter":"FM20191221000120","contractName":"单据号码","changeBefore":"FM20191221000119"}]}

var arr = dataArr.data

for (var i = 0; i < arr.length; i++) {
    if(arr[i].contractName === '单据号码'){
       var obj = arr[i];
  arr.splice(i, 1);

  break
    }
}
  arr.unshift(obj);
console.log(arr)

你可能感兴趣的:(javaScript)