Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

insert element in array at specific position javascript with loop

// Insert value at specific position with loop.
const data = [32, 1, 43, 76, 87]
const position = 2
let newValue = 69
for (let i = data.length - 1; i >= 0; i--) {
	if (i >= position) {
		data[i + 1] = data[i]
		if (i === position) {
			data[i] = newValue
		}
	}
}

console.log("===> :: data", data)
 
PREVIOUS NEXT
Tagged: #insert #element #array #specific #position #javascript #loop
ADD COMMENT
Topic
Name
5+8 =