admin管理员组文章数量:1134247
I have an array of objects. I want to move a selected object to the last position in the array. How do I do this in javascript or jquery?
Here is some code I have:
var sortedProductRow = this.product_row;
for (var s in sortedProductRow) {
if (sortedProductRow[s]["parent_product_type"] != "")
// Move this object to last position in the array
}
I'm looping through this with a for loop, and I want the output to be ordered so that all objects that does not have a "parent_product_type" value comes first, then those with a value.
I have an array of objects. I want to move a selected object to the last position in the array. How do I do this in javascript or jquery?
Here is some code I have:
var sortedProductRow = this.product_row;
for (var s in sortedProductRow) {
if (sortedProductRow[s]["parent_product_type"] != "")
// Move this object to last position in the array
}
I'm looping through this with a for loop, and I want the output to be ordered so that all objects that does not have a "parent_product_type" value comes first, then those with a value.
Share Improve this question edited Feb 6, 2020 at 12:43 Paul 8101 gold badge8 silver badges12 bronze badges asked Jul 23, 2014 at 11:33 Johan DahlJohan Dahl 1,7423 gold badges20 silver badges36 bronze badges 3 |9 Answers
Reset to default 157to move an element (of which you know the index) to the end of an array, do this:
array.push(array.splice(index, 1)[0]);
If you don't have the index, and only the element, then do this:
array.push(array.splice(array.indexOf(element), 1)[0]);
Example:
var arr = [1, 2, 6, 3, 4, 5];
arr.push(arr.splice(arr.indexOf(6), 1)[0]);
console.log(arr); // [1, 2, 3, 4, 5, 6]
NOTE:
this only works with Arrays (created with the
[ ... ]
syntax orArray()
) not with Objects (created with the{ ... }
syntax orObject()
)
Moving the first element of an array to the end of the same array
var a = [5,1,2,3,4];
a.push(a.shift());
console.log(a); // [1,2,3,4,5]
or this way
var a = [5,1,2,3,4];
var b = a.shift();
a[a.length] = b;
console.log(a); // [1,2,3,4,5]
Moving any element of an array to any position in the same array
// move element '5' (index = 2) to the end (index = 4)
var a = [1, 2, 5, 4, 3];
a.splice(4,0,a.splice(2,1)[0]);
console.log(a); // [1, 2, 4, 3, 5]
or it could be converted to a prototype as well, like this where x
represents the current position of element while y
represents the new position in array
var a = [1, 2, 5, 4, 3];
Array.prototype.move = function(x, y){
this.splice(y, 0, this.splice(x, 1)[0]);
return this;
};
a.move(2,4);
console.log(a); // ["1", "2", "4", "3", "5"]
Answer to the @jkalandarov comment
function moveToTheEnd(arr, word){
arr.map((elem, index) => {
if(elem.toLowerCase() === word.toLowerCase()){
arr.splice(index, 1);
arr.push(elem);
}
})
return arr;
}
console.log(moveToTheEnd(["Banana", "Orange", "Apple", "Mango", "Lemon"],"Orange"));
Immutable way:
const changedArr = [...prevArr.filter(a => a !== element), element]
This is more clean, without using the array index of [0]
const colors = ['white', 'black', 'red', 'blue', 'green'];
// will push the blue to the end of the array
colors.push(colors.splice(colors.indexOf('blue'), 1).pop());
console.debug(colors);
// ["white", "black", "red", "green", "blue"]
Using an anonymous function you can pass in the array and the value to filter by.
let concatToEnd = function (arr, val) {
return arr.filter(function(x) {
return x !== val; // filter items not equal to value
}).concat(arr.filter(function(x) { // concatonate to filtered array
return x === val; // filter items equal to value
})
);
}
// invoke
concatToEnd(array, 'parent_product_type');
You could probably shorten this further:
let concatToEnd = (arr,val) => arr.filter(x => x !== val).concat(arr.filter(x => x === val))
This function filters the items which do not equal the value passed in, then concatenates the result (to the end of the filtered array) of another filter
function which filters out the items which do equal the value you've passed in.
This function essentially separates the array into 2 filtered parts and then concatenates them back together
This hasn't been tested for your use-case, but I've used something similar to move all numbers of an array to the end of the index.
Move any element to last position - for lodash users:
const array = ['A', 'B', 'C', 'D'] // output: A, B, C, D
// finds index of value 'B' and removes it
_.pull(array , 'B') // output: A, C, D
// adds value of 'B' to last position
_.concat(array , 'B') // output: A, C, D, B
Moving all items equal so something to the end can also be done by concat.
const myArray = [1, 0, 3, 5, 0, 'a', 3, 's']
const moveZerosToEnd = (arr) => {
return arr.filter(item => item !== 0).concat(arr.filter(item => item === 0))
}
console.log(myArray) // [1, 0, 3, 5, 0, 'a', 3, 's']
console.log(moveZerosToEnd(myArray)) // [1, 3, 5, 'a', 3, 's', 0, 0]
You can move any number of items by splicing them, then spreading them into a push.
const numberOfItems = 3;
let items = [1,2,3,4,5,6,7,8,9];
items.push(...items.splice(0, itemsToMove))
Or you can try with sort. Maybe little bit slower but works at node-v8.
const arr = ['a', 'f', 'b', 'c', 'd', 'e'];
arr.sort((_x, y) => {
if (y === 'f') { // 'f' is the item that I want to move.
return -1;
}
return 0;
})
This works as inplace array sort method.
本文标签: javascriptMove item in array to last positionStack Overflow
版权声明:本文标题:javascript - Move item in array to last position - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736837157a1954940.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
sortedProductRow
is an object? you can iterate an array with for in as well (I don't say it's a good idea, but it's possible) – Ferdi265 Commented Jul 23, 2014 at 11:40