Move an array element forward using an object key

So, I have an array of objects;

[ { "foo": 2, "bar": "test" }, { "foo": 19, "bar": "value" }, { "foo": 7, "bar": "temp" } ] 

I need to move an object with a specific foo value to the beginning of the array. The value is always in the object, but there is no guarantee that the object will be in the array.

So, after running moveToFront(19); For example, I would have the following:

 [ { "foo": 19, "bar": "value" }, { "foo": 2, "bar": "test" }, { "foo": 7, "bar": "temp" } ] 

How can I do it?

+8
source share
5 answers

This should be pretty trivial: you search your array until you find the item you are looking for, then you splice and unshift return it to the beginning. Something like that:

 // 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). } 

If there is no element with the corresponding foo value, this will do nothing for your array. You can handle the error message with this.

+9
source

Shortest path: Array.some

The some() method checks to see if at least one element in the array has passed the test implemented by the provided function. Returns a boolean value.

 var data = [{"foo":2}, {"foo":19}, {"foo":7}, {"foo":22}] // move {foo:7} to the front data.some(item => item.foo == 7 && data.unshift(item)) // print result console.log(data) 

If you do not want to modify the original array, you can do the following:

 var data = [{"foo":2}, {"foo":19}, {"foo":7}, {"foo":22}] // move {foo:7} to the front const clonedData = [...data] clonedData.some((item, i, arr) => item.foo == 7 && arr.unshift(item)) // print result console.log(clonedData) 


FindIndex method will be useful

The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

 var data = [{"foo":2}, {"foo":19}, {"foo":7}, {"foo":22}] // find the index of the target array item: var itemIndex = data.findIndex(item => item.foo == 7); data.splice( 0, // new index, 0, // no removal data.splice(itemIndex, 1)[0] // detach the item and return it ); // print result console.log(data) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

If you use lodash and you need to have legacy browser support, use the _.findIndex method:

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

This will move the Array object with the key "foo": 19 to the beginning of the array.

+7
source

You can iterate over the array, find the element you need, splic it, and concatenate the rest of the array in the merged array.

 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); 
+1
source

Search for any value in each property, the first match wins. This seems very fast due to the use of the "some" method and the interruption of iteration over the array if the condition is met.

'some' performs a callback function once for each element present in the array, until it finds one where the callback returns the true value. If such an element is found, some () immediately returns true. Mutation in place ...

 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); 
0
source

Another solution. Mutation in place ...

 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); 
0
source

Source: https://habr.com/ru/post/1240375/


All Articles