通过对象键将数组项移到前面

时间:2016-01-11 18:58:37

标签: javascript arrays

所以我有一个对象数组;

// get time in HH:mm:ss format
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let str = dateFormatter.stringFromDate(date)
print(str)

我需要将具有特定值[ { "foo": 2, "bar": "test" }, { "foo": 19, "bar": "value" }, { "foo": 7, "bar": "temp" } ] 的对象移动到数组的开头。值始终在对象中,但不保证对象将在数组中。

因此,在运行foo之后,我有以下内容:

moveToFront(19);

我将如何做到这一点?

5 个答案:

答案 0 :(得分:10)

这应该是相当简单的,你搜索你的数组,直到你找到你想要的项目,然后你splice出来,unshift它回到开头。像这样:

// foo is the target value of foo you are looking for
// arr is your array of items
// NOTE: this is mutating. Your array will be changed (unless the item isn't found)
function promote(foo, arr) {
    for (var i=0; i < arr.length; i++) {
        if (arr[i].foo === foo) {
            var a = arr.splice(i,1);   // removes the item
            arr.unshift(a[0]);         // adds it back to the beginning
            break;
        }
    }
    // Matching item wasn't found. Array is unchanged, but you could do something
    // else here if you wish (like an error message).
}

如果没有匹配foo值的项目,那么这对您的数组无效。如果需要,您可以使用错误消息处理它。

答案 1 :(得分:5)

最短路:Array.some

&#13;
&#13;
var data = [
    {
        "foo": 2,
        "bar": "test"
    },
    {
        "foo": 19,
        "bar": "value"
    },
    {
        "foo": 7,
        "bar": "temp"
    },
    {
        "foo": 22,
        "bar": "temp"
    }
];

// move {foo:7} to the front
data.some(item => item.foo == 7 && data.unshift(item))


// print result
console.log(data)
&#13;
&#13;
&#13;

findIndex方法将有所帮助

&#13;
&#13;
var data = [
    {
        "foo": 2,
        "bar": "test"
    },
    {
        "foo": 19,
        "bar": "value"
    },
    {
        "foo": 7,
        "bar": "temp"
    }
];

// find the index of the target array item:
var itemIndex = data.findIndex(item => item.foo == 19); 



data.splice(
    0,                           // new index,
    0,                           // no removal
    data.splice(itemIndex, 1)[0] // detach the item and return it
);


// print result
console.log(data)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

  

如果您使用 lodash ,则需要留下遗产   浏览器支持,使用_.findIndex方法:

     

_.findIndex(data, {foo:19});

这将使用键"foo": 19将数组对象移动到数组的开头。

答案 2 :(得分:0)

您可以迭代数组,找到正确的元素,拼接它并将数组的其余部分连接到拼接数组。

var collection = [
  {
    foo: 15,
    bar: true
  },
  {
    foo: 19,
    bar: false
  }
];

function moveToFront(x) {
  for (var i = 0; i < collection.length; i++) {
    if (collection[i].foo === x) {
      collection = collection.splice(i, 1).concat(collection);
      break;
    }
  }
}

moveToFront(19);

console.log(collection);

答案 3 :(得分:0)

搜索每个属性中的任何值,首先匹配胜利。它似乎非常快,因为如果满足条件,使用方法'some'并打破迭代,然后满足条件。

'some'对数组中的每个元素执行一次回调函数,直到找到一个回调返回true值的元素。如果找到这样的元素,some()会立即返回true。突变已经到位......

var collection = [
    {
        "foo": 2,
        "bar": "test"
    },
    {
        "foo": 19,
        "bar": "value"
    },
    {
        "foo": 7,
        "bar": "temp"
    }
];


function moveToFront(searchValue) {

    var idx, exists;

    for (idx = 0; idx < collection.length; idx++) {
            exists = Object.keys(collection[idx]).some(function (key) {
            return collection[idx][key] === searchValue
        });
        if (exists) break;
    }

    collection.unshift(collection[idx]);
    collection.splice(idx + 1, 1);

}

moveToFront("temp"); // or moveToFront(19); or move whatever
console.log(collection);

答案 4 :(得分:0)

另一个解决方案。变异到位......

var collection = [
    {
        "foo": 2,
        "bar": "test"
    },
    {
        "foo": 19,
        "bar": "value"
    },
    {
        "foo": 7,
        "bar": "temp"
    }
];


function moveToFront(property, value, col) {
    col.reduce(function (prev, current, idx, obj) {
        if (current[property] != value) {
            return obj;
        } else {
            obj.unshift(obj[idx]);
            obj.splice(idx + 1, 1);
        }
    });
}

moveToFront('foo', 7, collection);
console.log(collection);